我试图编写一个函数,在Woocommerce单一产品页面上放置一个按钮,当点击它时,它会下载一个CSV,其中包含所有Woocommerce数据。
目前,如果我把代码放在functions.php中,按钮会点击并打开一个空白选项卡,但没有CSV。
// Add Download CSV button on product page
add_action( 'woocommerce_single_product_summary', 'add_download_csv_button', 25 );
function add_download_csv_button() {
global $product;
echo '<a href="' . get_home_url() . '/export-csv/?product_id=' . $product->get_id() . '" class="button">Download CSV</a>';
}
// Generate CSV file on button click
add_action( 'template_redirect', 'generate_csv_file' );
function generate_csv_file() {
if ( isset( $_GET['product_id'] ) && $_GET['product_id'] != '' ) {
$product_id = intval( $_GET['product_id'] );
$product = wc_get_product( $product_id );
// Set CSV headers
header( 'Content-Type: text/csv; charset=utf-8' );
header( 'Content-Disposition: attachment; filename=product-' . $product_id . '.csv' );
// Create CSV file
$output = fopen( 'php://output', 'w' );
fputcsv( $output, array( 'Product Name', 'Product SKU', 'Product Description', 'Product Price' ) );
fputcsv( $output, array( $product->get_name(), $product->get_sku(), $product->get_description(), $product->get_price() ) );
fclose( $output );
exit;
}
}
2条答案
按热度按时间kxxlusnw1#
也许这会起作用,如果我们对您的
echo
进行调整并替换:add_action( 'template_redirect', 'generate_csv_file' );
与
add_action( 'init', 'generate_csv_file' );
trnvg8h32#
要向WooCommerce单一产品页面添加一个按钮,当单击该按钮时,将下载包含所有WooCommerce数据的CSV,您可以按照以下步骤操作:
**1.**首先创建一个函数,生成一个包含所有必要数据的CSV文件。您可以使用
wc_get_orders
函数获取所有订单,并循环获取所需数据。示例如下:**2.**接下来,创建一个按钮,点击时调用
generate_csv
函数。您可以使用woocommerce_single_product_summary
动作钩子将按钮添加到WooCommerce单品页面。示例如下:**3.**最后,创建一个Map到generate_csv函数的自定义端点。您可以使用woocommerce_API_{endpoint}过滤器为您的函数创建一个自定义端点。示例如下:
有了这些步骤,你现在应该在你的WooCommerce单一产品页面上有一个按钮,当点击它时,它会下载一个包含所有必要数据的CSV文件。