Custom button next to the “ADD TO CART” button WooCommerce based on product type

I want to add a custom "View Demo" button next to the "Add to Cart" button in WooCommerce based on the type of product, both on the store’s main page and on a separate product page.

I have taken the following steps:

Add code to header.php theme file:

 <script>var url_demo = "<?php echo the_field('url_demo'); ?>"</script> 

Add jQuery script using TC Custom JavaScript plugin:

 jQuery(function($) { $('.add_to_cart_button, .single_add_to_cart_button').after(' <a class="button demo_button" style="padding-right: 0.75em;padding-left: 0.75em;margin-left: 8px; background-color: #0ebc30;" href="'+url_demo+'" target="_blank">View Demo</a>'); }); 

It works, the custom button "Open demo" is shown on the main page of the store and on a separate product page.

But I have some kind of problem, the link for the button "View demo" is correct only on the page "One product", and on the main page of the store the button "Open demo", a link to the same URL. Is my code wrong?

My questions are: how to add the button "View demo" (both on the main page of the store, and on the page of one product), which are displayed only for the type of product, for example, only in the Subject category? Finally, is there any other way to add a demo link without editing the header.php file, such as the method above? I just expect the header.php file to reset if the theme is updated.

+6
source share
3 answers

I use another way to do this: WooCommerce hooks .

You no longer need the jQuery script, as well as the javascript located in your header.php file, so you can erase them.

Using get_field() instead of the_field (thanks to Deepti chipdey ) to get only the value concatenated into an echoed string.

Paste this piece of code into the function.php file located in your active child theme or theme folder:

 function wc_shop_demo_button() { echo '<a class="button demo_button" style="padding-right: 0.75em;padding-left: 0.75em;margin-left: 8px; background-color: #0ebc30;" href="'.get_field( "url_demo" ).'" target="_blank">View Demo</a>'; } add_action( 'woocommerce_after_shop_loop_item', 'wc_shop_demo_button', 20 ); add_action( 'woocommerce_after_add_to_cart_button', 'wc_shop_demo_button', 20 ); 

I have hooks used to display the Add to Cart button on the store page and on the pages of one product, to display the Open demo button after that, buy priority.

+4
source

Change

 the_field('url_demo'); 

to

  get_field('url_demo'); 
+2
source

For some reason LoicTheAztec's answer did not do this for me.

Here's what worked:

 function wc_shop_demo_button() { echo '<a class="button demo_button" href="'.get_field( "url_demo" ).'" target="_blank">View Demo</a>'; } add_action( 'woocommerce_after_add_to_cart_button', 'wc_shop_demo_button' ); 

Hope someone helps on their journey.

+1
source

All Articles