blkedy
blkedy

Reputation: 1243

Add Woocommerce parent category to WP 'body' class

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

Every time I go within a child category the parent category is no longer within the body class.

Could something like below be edited to find the parent category and add within the body tag?

Maybe a term like "product_parent_cat"? Tried this and searched their API but no success..

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

Upvotes: 7

Views: 3948

Answers (1)

birgire
birgire

Reputation: 11378

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 the parent product category slugs to the body class.

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

Upvotes: 11

Related Questions