phpwoocommerceglobal-variablesproductshortcode

Display product excerpt only when using WooCommerce product_category shortcode


I'm looking to use something like [product_category excerpt="yes"] in order to display product short description only when needed.

I'm using this function below to add the product short description:

    add_action( 'woocommerce_after_shop_loop_item_title', 'output_product_excerpt', 35 );

    function output_product_excerpt() {
    global $post;
    echo $post->post_excerpt;
    }

But it adds the product description globally (everywhere), including "related products" and "upsells products" which is not needed.

How to restrict displayed product description only to [product_category] shortcode?


Solution

  • You can't use an argument in WooCommerce [product_category] shortcode to display or not the product short description, as the shortcode arguments are used to filter the number of displayed products based on those arguments.

    What you can do is to restrict short description to be displayed only for "product_category" shortcode from your current function code like:

    add_action( 'woocommerce_after_shop_loop_item_title', 'product_category_shortcode_display_excerpt', 35 );
    function product_category_shortcode_display_excerpt() {
        global $post, $woocommerce_loop;
    
        if ( isset($woocommerce_loop['name'], $woocommerce_loop['is_shortcode']) 
        && $woocommerce_loop['name'] === 'product_category' && $woocommerce_loop['is_shortcode'] ) {
            echo $post->post_excerpt;
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.