Home > database >  Woocommerce - Displaying only the parent category under the product title
Woocommerce - Displaying only the parent category under the product title

Time:04-11

I'm running this script to show the product category under the product titles on my website:

function wpa89819_wc_single_product(){

    $product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );

    if ( $product_cats && ! is_wp_error ( $product_cats ) ){

        $single_cat = array_shift( $product_cats ); ?>

        <h6 ><?php echo $single_cat->name; ?></h6>

<?php }
}
add_action( 'woocommerce_after_shop_loop_item_title', 'wpa89819_wc_single_product', 2 );

It's working, however not how I want it to. I would like to only show the parent category for every product. At the moment it seems to pick the lowest child category.

I'm just starting to learn php, so any help is much appreciated.

CodePudding user response:

Assuming that your parent categories are top level categories - i.e., without parents of their own - you could use the following code safely:

function wpa89819_wc_single_product() {

    $product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );

    if ( ! is_wp_error ( $product_cats ) ) {  //probably not necessary, but I see you're begin extra-careful...

        foreach( $product_cats as $cat ) {

            if ( 0 === $cat->parent ) { // top-level cat has "0" as parent ?>

                <h6 ><?php echo $single_cat->name; ?></h6>

            <?php }

        }

    }

}

add_action( 'woocommerce_after_shop_loop_item_title', 'wpa89819_wc_single_product', 2 );
  • Related