Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add shortcode below short description only for WooCommerce products having a specific tag

I found a code that can add a shortcode below the short description of a WooCommerce product:

add_filter('woocommerce_short_description','ts_add_text_short_descr');
function ts_add_text_short_descr($description){
   $text = do_shortcode('[my-shortcode]');
  return $description . $text;
}

Then I tried to add that shortcode to the short description, only if a product has a specific product tag:

add_filter('woocommerce_short_description', 'ts_add_text_short_descr');
function ts_add_text_short_descr($description) {
    global $product;   


    // Check if the product has a "VIP" tag
    $product_tags = wp_get_post_terms($product->get_id(), 'product_tag');
    $has_vip_tag = false;
    foreach ($product_tags as $tag) {
        if ($tag->slug === 'vip') {
            $has_vip_tag = true;
            break;
        }
    }

    // If the product has the tag "VIP", add the shortcode
    if ($has_vip_tag) {
        $text = do_shortcode('[my-shortcode]');
        return $description . $text;
    } else {
        return $description;
    }
}

But it doesn’t seem to work. Is there any other way to do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simplify your code by using WordPress has_term() conditional function, to check if a product has a specific product tag, like:

add_filter( 'woocommerce_short_description', 'add_text_to_short_description_conditionally' );
function add_text_to_short_description_conditionally( $description ){
    global $post;

    if ( has_term( array('vip'), 'product_tag' ) ) {
        $description .= do_shortcode('[my-shortcode]');
    }
    return $description;
}

It should work.

Note that WordPress has_term() conditional function accept term ID(s), slug(s) or name(s).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading