Add Taxonomy Terms as CSS Classes to a Post

You can use the body_class filter in WordPress to add the Taxonomy Terms of a Custom Taxonomy as CSS classes to a post. The CSS class appears in the body element and is only used if the post has been assigned to the taxonomy.

The code goes in your functions.php file.


 add_filter( 'body_class', 'themeprefix_add_taxonomy_class' );
 // Add taxonomy terms name to body class
function themeprefix_add_taxonomy_class( $classes ){
    if( is_singular() ) {
        global $post;
        $taxonomy_terms = get_the_terms($post->ID, 'your_taxonomy'); // change to your taxonomy
        if ( $taxonomy_terms ) {
            foreach ( $taxonomy_terms as $taxonomy_term ) {
            $classes[] = 'tax_' . $taxonomy_term->slug;
    return $classes;

Change ‘your_taxonomy’ to the actual taxonomy, the body_class filter is fed the results from a foreach loop done on the custom taxonomy, if any of the terms of that custom taxonomy are used by the post, they are added to the $classes array, in the above instance they have a prefix of ‘tax_’ followed by the term – you can change this prefix to suit or simply not have one.

Leave all Comment