WordPress – Add Taxonomy Class to Body Tag
This function automatically modifies the body tag to include a new unique CSS class specific to any assigned categories or taxonomies. The class can then be used for advanced styling of those posts, pages or custom post types. So for example: If you wanted a blue page header for anything assigned to a category named “blue” you could easily achieve this.
add_filter( 'body_class', 'add_taxonomy_class' );
// Add taxonomy terms name to body class
function add_taxonomy_class( $classes ){
if( is_singular() ) {
global $post;
$taxonomy_terms = get_the_terms($post->ID, array( 'category' ) ); // add additional taxonomies to the array as needed
if ( $taxonomy_terms ) {
foreach ( $taxonomy_terms as $taxonomy_term ) {
$classes[] = 'tax_' . $taxonomy_term->slug;
}
}
}
return $classes;
}
add_filter( 'body_class', 'add_taxonomy_class' );

Leave a Reply
Want to join the discussion?Feel free to contribute!