I'm using woocommerce and have "virtual" and "downloadable" products. I want to create a shortcode to display a "Download" button for these products. Because there are so many products, I want to have a fixed shortcode to use for all products, not shortcode like [download id="123"].
I tried using this code and use [download_button] in short descreption but it doesn't work
function download_button_shortcode( $atts ) {
global $product;
$download_files = $product->get_downloads();
$download_url = isset( $download_files[0]['file'] ) ? $download_files[0]['file'] : '';
$button = '<a href="' . esc_url( $download_url ) . '" class="button">Download</a>';
return $button;
}
add_shortcode( 'download_button', 'download_button_shortcode' );
function download_button_shortcode($atts) {
global $product;
$download_files = $product->get_downloads();
if (!empty($download_files)) {
foreach ($download_files as $key => $download_file) {
$download_url = $download_file->get_file();
$button = '<a href="' . esc_url($download_url) . '" class="button">Download</a>';
return $button;
}
}
}
add_shortcode('download_button', 'download_button_shortcode');
Use the shortcode [download_button]