In the process of building a business directory using custom post types in WordPress 3.0, I had a need to style posts and pages differently. I came across this post about How to Create Dynamic Body Classes from @Nick_theGeek using get_the_category, but could not figure out how to adapt it to custom taxonomies.
After searching a little more, I found this forum post on WP Tavern from Michael Fields on how to add Custom Taxonomy as CSS Class. It works perfectly so I’ll share the code with you here:
add_filter( 'body_class', 'mysite_body_class', 10 );
if( !function_exists( 'mysite_body_class' ) ) {
/**
* Body Class.
* @since 2010-06-22
*/
function mysite_body_class( $classes ) {
if( is_tax() ) {
global $taxonomy;
if( !in_array( $taxonomy, $classes ) )
$classes[] = $taxonomy;
}
return $classes;
}
}
Alternatively if you want to add it to the post class, just replace body_class with post_class.
Or if you want to use the Taxonomy Terms as the class, use the following code, replacing ‘status’ with your taxonomy slug:
add_filter( 'post_class', 'mysite_post_class', 10, 3 );
if( !function_exists( 'mysite_post_class' ) ) {
/**
* Append taxonomy terms to post class.
* @since 2010-07-10
*/
function mysite_post_class( $classes, $class, $ID ) {
$taxonomy = 'status';
$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;
}
}
Hi,
Thanks a lot for this, I’ve been struggling with the same issue… But I can’t seem to get how you call this function is your theme ?
I tried this :
<li class=" “>
But it doesn’t work.
Any help ?
This code should be added to your functions.php. It will then add body classes based on the taxonomy or term.
Worked like a charm! Thanks for this