Long story short, this solution shows a button on the single product template which links to a URL of your choice. If you leave the custom field empty, the button will not show. Now, we’re a big fan of Advanced Custom Fields (ACF) but we try to minimise the amount of plugins per solution. This particular solution introduces a new custom field in the product editor without the use of a plugin like ACF which allows you to enter a URL. This URL is where the user will go when they click the new View Demo button they’ll see on the single product template. If you sell music, this solution will be useful if you want to link to a short snippet of it. It may good if you sell an ebook and want to link to a preview chapter. If you sell templates for websites, this button will allow users to see a preview before buying. After implementing the code snippet, enter the appropriate URL in the product data metabox, then take a look at the product page…see where the View Demo button takes you.
/**
* Snippet Name: WooCommerce Custom Product Data Metabox For Custom Button Link
* Snippet Author: ecommercehints.com
*/
add_action ('woocommerce_product_options_advanced', 'ecommercehints_product_data_metabox');
function ecommercehints_product_data_metabox() {
echo '';
woocommerce_wp_text_input (array (
'id' => 'demo_url',
'value' => get_post_meta (get_the_ID(), 'demo_url', true),
'label' => 'Demo URL',
'description' => 'The button link'
));
echo '';
}
add_action ('woocommerce_process_product_meta', 'ecommercehints_save_field_on_update', 10, 2);
function ecommercehints_save_field_on_update ($id, $post) {
update_post_meta ($id, 'demo_url', $_POST['demo_url']);
}
function ecommercehints_content_after_add_to_cart_form() {
global $product;
$demo_url = $product->get_meta ('demo_url');
echo 'View Demo';
};
add_action ('woocommerce_after_add_to_cart_form', 'ecommercehints_content_after_add_to_cart_form', 10, 0);