How to add Woocommerce parent category to WP ‘body’ class?

In this tutorial we’ll learn how to add woocommerce parent category to WP body class. By default woocommerce won’t add category classes to the body tag of category pages. Here is the default classes being added to body tag of category pages:

Wocommerce

Now to add category classes to body tag, add the following lines of code at the end of your theme’s functions.php file:

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

You can access functions.php file here.

Wocommerce

Now after adding the code, go to a category page and inspect element by right clicking on page.

Now if you go to body tag, you’ll see parent class being added there.

Wocommerce

 

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

1 thought on “How to add Woocommerce parent category to WP ‘body’ class?”

  1. OR… If you don’t want to use the ugliest code ever created you could use:

    add_filter( ‘body_class’, ‘wc_cat_names’ );
    function wc_cat_names( $classes ) {
    if(is_product()){
    global $post;
    $terms = get_the_terms( $post->ID, ‘product_cat’ );
    foreach ($terms as $term) {
    $classes[] = $term->slug;
    }
    }
    return $classes;
    }

Leave a Comment

Your email address will not be published. Required fields are marked *