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:


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.


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.



Editorial Staff

ThemeLocation Provides Wordpress & Woocommerce development & Customization services. Have a Project? Contact To discuss

Leave a Reply

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