【问题标题】:Export Woocommerce product data to CSV on button click单击按钮将 Woocommerce 产品数据导出到 CSV
【发布时间】:2023-02-16 17:53:51
【问题描述】:

我有这段代码是为了获取 woocommerce 产品数据(从单个产品页面)并在单击按钮时将其导出到可下载的 CSV,但是每当我单击按钮时它只会刷新页面?


<?php

// Define the function to export a WooCommerce product to CSV
function export_product_to_csv() {

  // Get the product ID from the URL parameter
  $product_id = $_GET['product_id'];

  // Get the product data from the database
  $product = wc_get_product($product_id);

  // Create the CSV file
  $csv_file = fopen('product.csv', 'w');

  // Write the header row to the CSV file
  fputcsv($csv_file, array('Product Name', 'SKU', 'Price', 'Stock Status'));

  // Write the product data to the CSV file
  fputcsv($csv_file, array($product->get_name(), $product->get_sku(), $product->get_price(), $product->get_stock_status()));

  // Close the CSV file
  fclose($csv_file);

  // Download the CSV file
  header('Content-Type: application/csv');
  header('Content-Disposition: attachment; filename="product.csv";');
  readfile('product.csv');
  exit;
}

// Check if the export button was clicked
if (isset($_POST['export'])) {
  export_product_to_csv();
}

?>

<!-- Add the export button to the WooCommerce product page -->
<form method="post">
  <input type="hidden" name="product_id" value="<?php echo get_the_ID(); ?>">
  <button type="submit" name="export">Export to CSV</button>
</form>

【问题讨论】:

    标签: php wordpress csv woocommerce


    【解决方案1】:

    似乎导出功能是在带有 POST 请求的表单提交事件上触发的,但按钮实际上并未提交表单。

    要解决此问题,您可以修改按钮以提交表单,方法是将其更改为带有“提交”按钮的输入类型:

    <input type="hidden" name="product_id" value="<?php echo get_the_ID(); ?>">
    <input type="submit" name="export" value="Export to CSV">
    

    通过此修改,单击“导出为 CSV”按钮将提交表单并触发 export_product_to_csv() 函数,该函数应下载 CSV 文件而不是刷新页面。

    【讨论】:

      猜你喜欢
      • 2021-03-15
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      相关资源
      最近更新 更多