2

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Hi @FabioMiliWeb, not beeing an expert in wordpress this looks like a recursive function on `$term` is needed, to get the parents until you arrived at the top category. But there might be already a shorthand function build inside of wordpress. – Andreas Apr 21 '20 at 21:46
  • Ah yes, and it is a good idea to ask wordpress related questions directly in the wordpress branch of stack overflow: https://wordpress.stackexchange.com/ (for the next question ;) ) – Andreas Apr 21 '20 at 21:46
  • Thanks Andreas, I'll do it. – FabioMiliWeb Apr 22 '20 at 10:15

1 Answers1

1

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399