Add parent Woocommerce category to WP 'body' class

I am trying to add a parent product category from Woocommerce as a class in wordpress' body .

Every time I go to a child category, the parent category is no longer included in the body class.

Can I edit something like below to find the parent category and add to the body tag?

Maybe a term like "product_parent_cat"? I tried this and looked for their API, but did not succeed.

 function woo_custom_taxonomy_in_body_class( $classes ){ $custom_terms = get_the_terms(0, 'product_cat'); if ($custom_terms) { foreach ($custom_terms as $custom_term) { $classes[] = 'product_cat_' . $custom_term->slug; } } return $classes; } add_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' ); 
+6
source share
1 answer

You can try this modification (untested):

 function woo_custom_taxonomy_in_body_class( $classes ){ $custom_terms = get_the_terms(0, 'product_cat'); if ($custom_terms) { foreach ($custom_terms as $custom_term) { // Check if the parent category exists: if( $custom_term->parent > 0 ) { // Get the parent product category: $parent = get_term( $custom_term->parent, 'product_cat' ); // Append the parent class: if ( ! is_wp_error( $parent ) ) $classes[] = 'product_parent_cat_' . $parent->slug; } $classes[] = 'product_cat_' . $custom_term->slug; } } return $classes; } add_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' ); 

to add parent product categories to the body class.

Here we use the parent property for the term object returned by get_term() .

+7
source

Source: https://habr.com/ru/post/976171/


All Articles