Lubo Masura
Lubo Masura

Reputation: 1053

Woocommerce - Display a parent category name in a subcategory

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.

Upvotes: 0

Views: 456

Answers (1)

Orbital
Orbital

Reputation: 966

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' );

Upvotes: 1

Related Questions