Add class to website based on post taxonomy

I want to write a class to the body of all pages posts and custom posts (IE entire site)

I am using a front end editor that allows logged in users to edit posts and keep them out of the back-end.

  • I have a custom post-type "emergency status"
  • It contains one post with a taxonomy "status"
  • It has the terms extreme, severe, very-high, high, moderate.

I want to add a filter that checks the taxonomy of that post and then adds it to the body of the site.

Topic body-class php taxonomy Wordpress

Category Web


  • 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.

WordPress already does this if your theme has been built correctly. Specifically, WP will add classes to the body tag if you used body_class and to the posts containing element if you used post_class

For example, if you install WordPress, the default Hello World post is uncategorized, and has the following classes:

post-1 post type-post status-publish format-standard hentry category-uncategorized entry

Notice the category-uncategorized class.

Similarly the <body> tag has these classes:

post-template-default single single-post postid-1 single-format-standard wp-embed-responsive singular image-filters-enabled

Other classes get added depending on the context, e.g. a class gets added if the admin toolbar is showing, or if the user is logged in, etc

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.