Tasos Seit
Tasos Seit

Reputation: 41

How to echo a shortcode in a specific product category

I have this php code and it displays a button in the single product page. Everything works fine but the button generated from the shortcode is displayed in EVERY product category. I want to display the button from shortcode ONLY in a specific product category.

<?php
    add_action ('woocommerce_after_add_to_cart_button', 'quote'); //action

    function quote()
    
     {      
      echo do_shortcode( '[wpb-quote-button id="14"]' ); //shortcode
     }

    ?>

I tried this but the site crashed


        add_action ('woocommerce_after_add_to_cart_button', 'quote'); //action
    
        function quote()
        
           if ( in_category( $cat 'category-slug' ) ) {


                
          echo do_shortcode( '[wpb-quote-button id="14"]' ); //shortcode
         

                                       }

Upvotes: 1

Views: 397

Answers (1)

Ashendale
Ashendale

Reputation: 136

Let's see if I can help you! First of all you're missing two curly brackets in your function and that is why your site crashed. You need to wrap your function with the curly brackets to avoid this.

What I think you want to do is to only execute the shortcode if it's a certain product category archive page. You can do this by using if( is_product_category() ) You need to define the category either by slug, id or title.

Try this function and change "example" to the title of your category. Let me know how it works out!

add_action ('woocommerce_after_add_to_cart_button', 'quote'); //action
function quote() {
        if( is_product_category('example') ) {   //change "example" to category title, id or slug 
          echo do_shortcode( '[wpb-quote-button id="14"]' ); //shortcode
          }
}

Upvotes: 1

Related Questions