I’m trying to code a function to put a button on a Woocommerce Single Product Page, that when clicked it downloads a CSV with all woocommmerce data on it.
Currently, if I put the code in functions.php, the button clicks and opens a blank tab, but no CSV. Any idea how to fix or what the problem may be?
// 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
Answers
Maybe this will work, what if we make a tweak to your
echo
and replace:add_action( 'template_redirect', 'generate_csv_file' );
with
add_action( 'init', 'generate_csv_file' );
To add a button to a WooCommerce Single Product Page that, when clicked, downloads a CSV with all WooCommerce data, you can follow these steps:
1. First, create a function that generates a CSV file with all the necessary data. You can use the
wc_get_orders
function to get all the orders and loop through them to get the required data. Here’s an example:2. Next, create a button that calls the
generate_csv
function when clicked. You can add the button to the WooCommerce Single Product Page by using thewoocommerce_single_product_summary
action hook. Here’s an example:3. Finally, create a custom endpoint that maps to the generate_csv function. You can use the woocommerce_api_{endpoint} filter to create a custom endpoint for your function. Here’s an example:
With these steps, you should now have a button on your WooCommerce Single Product Page that, when clicked, downloads a CSV file with all the necessary data.