body_class filter does not seem to work properly when using the filter
-
Hi there,
I need to add the name of the topmost product category as a css class to the <body> tag of the rendered pages. For that purpose i have this code in the functions.php of my theme:add_filter( 'body_class', 'wc_add_topmost_cat_name' ); function wc_add_topmost_cat_name( $classes ) { if(is_woocommerce()){ global $wp_query; $q_obj = $wp_query->get_queried_object(); $cat_id = $q_obj->term_id; $ancestors = get_ancestors($cat_id, 'product_cat'); $ancestors = array_reverse($ancestors); $origin_ancestor = get_term_by("id", $ancestors[0], "product_cat"); $origin_ancestor_id = $origin_ancestor->term_id; $origin_ancestor_name = strtolower($origin_ancestor->name); $classes[] = $origin_ancestor_name; } return $classes; }
Above code works as expected if i enter the URL of any of my product categories directly.
However as soon as i click on any product categories in the filter generated by this plugin, the above code has no effect at all. After some digging in the code i found that if i comment out line 767 inside index.php ($wp_query->is_tax?=?false;), then i get the desired class name, but it also affects what product categories get rendered in the filter.
There must be a way to add category names to the body class even if using this plugin to generate a category tree for navigation, but i simply can not figure it out. Any help is appreciated!
- The topic ‘body_class filter does not seem to work properly when using the filter’ is closed to new replies.