点击按钮将Woocommerce产品数据导出到CSV

ukdjmx9f  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(126)

我有这个代码,这是为了采取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>
xqnpmsa8

xqnpmsa81#

导出功能似乎是在具有POST请求的表单提交事件上触发的,但是按钮实际上并没有提交表单。
要解决此问题,您可以修改提交表单的按钮,方法是将其更改为带有“提交”按钮的输入类型:

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

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

相关问题