简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM