如何修改代码实现点击按钮下载WooCommerce商品SKU、描述、价格CSV
WooCommerce商品页面添加商品详情CSV导出功能
下面是完整的实现方案,分两步完成:
1. 在商品页面添加导出按钮
将以下代码添加到主题的functions.php文件或自定义插件中,它会在商品详情页的摘要区域添加一个导出CSV的按钮:
add_action('woocommerce_single_product_summary', 'add_product_csv_export_button', 35); function add_product_csv_export_button() { $product_id = get_the_ID(); echo '<a href="' . esc_url(add_query_arg(array('action' => 'export_product_csv', 'product_id' => $product_id))) . '" class="button">导出商品详情CSV</a>'; }
2. 实现CSV导出的处理逻辑
同样添加到functions.php或自定义插件中,处理导出请求并生成包含SKU、描述、价格的CSV文件:
add_action('init', 'handle_product_csv_export'); function handle_product_csv_export() { // 验证请求参数,确认是导出操作且商品ID有效 if (!isset($_GET['action']) || $_GET['action'] !== 'export_product_csv' || !isset($_GET['product_id']) || !is_numeric($_GET['product_id'])) { return; } $product_id = intval($_GET['product_id']); $product = wc_get_product($product_id); // 确认商品存在 if (!$product) { wp_die('无效的商品ID'); } // 设置CSV响应头 header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="商品详情_' . $product->get_sku() . '.csv"'); // 清理输出缓冲,避免多余内容干扰CSV ob_end_clean(); $output = fopen('php://output', 'w'); // 写入CSV表头 $header_args = array('SKU', '描述', '价格'); fputcsv($output, $header_args); // 写入商品数据 $product_data = array( $product->get_sku(), // 移除HTML标签,保留纯文本描述 wp_strip_all_tags($product->get_description()), wc_price($product->get_price(), array('currency' => get_woocommerce_currency())) ); fputcsv($output, $product_data); fclose($output); exit; }
原代码问题说明
- 原代码中
$data数组里的内容是字符串形式的函数调用('$product->get_sku();'),不会执行,直接输出了字符串本身,需要替换为实际的函数调用获取数据。 - 没有正确获取当前商品的
$product对象,需要通过商品ID实例化WooCommerce商品对象。 - 输出缓冲清理的位置调整到header之前,避免之前的页面输出导致header发送失败。
- 优化了文件名,加入商品SKU方便区分不同商品的导出文件。
- 对商品描述做了HTML标签清理,避免CSV中混入HTML代码;价格使用WooCommerce自带的格式化函数,输出带货币符号的价格。
内容的提问来源于stack exchange,提问作者Paul M
相关产品推荐
相关产品推荐

