Trying to turn the add to cart button into a download link on a Woocommerce site (for free downloadable items).
The code I have set up below does that, but it is also duplicating the add to cart button. So I end up with the file download link + an additional add to cart button.
What am I missing?
Here is that code:
remove_action( 'woocommerce_single_product_summary',
'woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary',
'itl_woocommerce_template_single_add_to_cart', 30 );
/*
* replace WooCommerce add-to-cart button with download link when product is
downloadable & free
*/
function itl_woocommerce_template_single_add_to_cart() {
global $product;
if ( $product->is_downloadable('yes') ) {
if ( $product->get_price() > 0 ) {
do_action( 'woocommerce_' . $product->product_type .
'_add_to_cart' );
} else {
$downloads = $product->get_files();
foreach( $downloads as $key => $download ) {
echo '<p class="download-link"><a href="' . esc_url(
$download['file'] ) . '">' . $download['name'] . '</a></p>';
}
}
} else {
do_action( 'woocommerce_' . $product->product_type . '_add_to_cart' );
}
}
I have revisited, corrected, compact and tested your code. So now its working for WC version 3+:
add_action( 'woocommerce_single_product_summary', 'customizing_single_add_to_cart', 1 );
function customizing_single_add_to_cart(){
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
add_action('woocommerce_single_product_summary', function(){
global $product;
if ( $product->is_downloadable() && $product->get_price() <= 0 )
foreach( $product->get_downloads() as $key => $download )
echo '<p class="download-link"><a href="' . esc_url( $download['file'] ) . '">' . $download['name'] . '</a></p>';
else
woocommerce_template_single_add_to_cart();
}, 30);
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works (in WooCommerce version 3+)