Custom Taxonomies in body class with parent slug
I have tried many answers here on stackoverflow but couldnt find a solution to my problem. I have created a custom post type called ph_products
and custom taxonomies with the name ph_category
.
Then I created some categories for that custom post type like this:
blue-products
blue-sub-products
green-products
red-products
I need to have body classes as following:
When on the ph_products-archive
page there should be a class with that slug in the body
When on one of the parent categories the respective slug should be in the body class
And when I am on one of the sub category archive pages I need to also have the parent category class
For example I am at the blue-sub-products
archive page I want to have blue-products, ph_products-archive, blue-sub-products
in the body class
Of course I need all of these classes in the respective single views of the products as well.
I use this piece of code to add the desired classes:
(thanks to https://alexanderdejong.com/wordpress/add-custom-taxonomies-body-class)
function atp_custom_taxonomy_body_class($classes, $class, $ID) {
$taxonomies_args = array(
'public' = true,
'_builtin' = false,
);
$taxonomies = get_taxonomies( $taxonomies_args, 'names', 'and' );
foreach ($taxonomies as $taxonomy) {
$terms = get_the_terms( (int) $ID, $taxonomy );
if ( ! empty( $terms ) ) {
foreach ( (array) $terms as $order = $term ) {
if ( ! in_array( $term-slug, $classes ) ) {
$classes[] = $term-slug;
}
}
}
}
return $classes;
}
add_filter( 'body_class', 'atp_custom_taxonomy_body_class', 10, 3 );
But this kinda adds the classes pretty weird for example when I am on the ph_products-archive
page I also get the category slugs of the last item posted there so if the last item is in the categories blue-products, blue-sub-products
I get these two slugs as classes as well although I am not at these category pages
Or when I am at the blue-products-archive
page I also get the blue-sub-products
category slug in the body class.
How can I only get the classes desired as described above?
Topic body-class custom-taxonomy custom-post-types Wordpress
Category Web