Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show h2 tag ONLY if there is a description in product category in Woocommerce

Our Woocommerce product category archive pages have an <h1> tag at the top followed by the grid of products as by default.

Now we have added an <h2> tag with the category name again at the bottom and under the <h2> tag is the description for that product category.

I have set this up in the archive-product.php adding this:

<h2 class="cat-desc-title"><?php woocommerce_page_title(); ?></h2>

However I was wondering if anyone knew a way to show this ONLY if there is a description displayed on this product category page.

How to write an if statement for that?

Any help is much appreciated.

like image 852
Patrick Avatar asked Dec 19 '25 07:12

Patrick


1 Answers

Yes this is possible adding some condition in an if statement like:

    <?php 
        if ( is_product_taxonomy() && 0 === absint( get_query_var( 'paged' ) ) ):

        $wp_term_obj = get_queried_object();

        if ( $wp_term_obj && ! empty( $wp_term_obj->description ) ):
    ?>

        <h2 class="woocommerce-products-header__title page-title"><?php woocommerce_page_title(); ?></h2>

    <?php endif; endif; ?>

This will display your <h2> title only if a description exist for the queried product category (or the product tag). This goes in archive-product.php. It is tested and works.

Now if you want to target specifically product category archives pages (but not product tag archives), you will replace is_product_taxonomy() by is_product_category().


Alternative Without overriding template files:

This could be embed in a hooked function instead of overriding the template, just as the displayed product category description, with a hook priority before 10.

So this could be done with something like:

add_action( 'woocommerce_archive_description', 'add_h2_title_before_archive_description', 5 );
function add_h2_title_before_archive_description() {
    if ( is_product_taxonomy() && 0 === absint( get_query_var( 'paged' ) ) ):
        $wp_term_obj = get_queried_object();

        if ( $wp_term_obj && ! empty( $wp_term_obj->description ) ):
        ?>
        <h2 class="woocommerce-products-header__title page-title"><?php woocommerce_page_title(); ?></h2>
        <?php
        endif; 
    endif;
}

Code goes in function.php file of your active child theme (or active theme).

Tested and works.

like image 69
LoicTheAztec Avatar answered Dec 21 '25 21:12

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!