Home > Mobile >  Woocommerce - Display a parent category name in a subcategory
Woocommerce - Display a parent category name in a subcategory

Time:09-22

I have a code which I use with a shortcode to get a parent category title. When I'm at the parent category I get the right title. When I'm at the subcategory, the parent category title does not show and instead of title I see the parent category ID. Do you have any idea how could I solve this problem?

/*get title*/
function woocommerce_category_title() {
    if ( is_product_category() ){
        $term      = get_queried_object();
        $term_title   = $term->parent > 0 ? $term->parent : $term->name;
            echo $term_title;
        }
    
}
add_shortcode( 'cattit', 'woocommerce_category_title' );

Thank you in advance.

CodePudding user response:

function woocommerce_category_title() {
    if ( is_product_category() ){
        $term      = get_queried_object();
        $term_title   = $term->parent > 0 ? $term->parent : $term->name;
        if($term->parent > 0) {
        $parent_term = get_term_by('ID', $term->parent, 'product_cat');
        $term_title = $parent_term->name;
        } else {
        $term_title = $term->name;
        }
            echo $term_title;
        }
    
}
add_shortcode( 'cattit', 'woocommerce_category_title' );
  • Related