FabioMiliWeb
FabioMiliWeb

Reputation: 23

Get top level parent product category as body class in WooCommerce

I need to get the TOP level category (not just the parent category) of a subcategory of products in Woocommerce.

I have this code to get the parent category id:

if (is_subcategory()) {
  $term = get_queried_object();
  $parent_id = $term->parent;
}

And this one makes $parent_id as a body class:

add_filter( 'body_class', 'parent_id_body_class' );
function parent_id_body_class( $classes ) {
    // add comprehensive text followed by parent id number to the $classes array
    $term = get_queried_object();
    $parent_id = $term->parent;
    $classes[] = 'parent-id-' . $parent_id;
    // return the $classes array
    return $classes;
}

All this works fine, but this is NOT the top level parent category. It's just the parent. I've got 3 levels of categories. I'm not very skilled in php yet... I've searched a lot but couldn't find how figure this out. Your help would be very appreciated. Thank You.

Upvotes: 2

Views: 2175

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253868

The following will allow you to display the top level parent product category term Id on the body classes (commented code):

add_filter( 'body_class', 'wc_product_cat_top_parent_id_body_class' );
function wc_product_cat_top_parent_id_body_class( $classes ) {
    // Only product category archives pages
    if ( is_product_category() ) {
        $taxonomy = 'product_cat'; // Woocommerce product category taxonomy

        // Get all parent terms Ids
        $parent_terms = get_ancestors( get_queried_object_id(), $taxonomy );

        // Only for product subcategories
        if ( sizeof( $parent_terms ) > 0 ) {
            // Loop through all parent terms Ids
            foreach ( $parent_terms as $parent_id ) {
                // Only the product category top level term Id
                if( get_term( $parent_id, $taxonomy )->parent == 0 ) {
                    $classes[] = 'top-parent-id-' . $parent_id;
                }
            }
        }
    }
    return $classes;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Upvotes: 1

Related Questions