Site logo

Archived topic

Change header background for category or pages

22 replies · Started by anamoore on May 12, 2015

Viewing posts 16–23 of 23

Thank you, it worked!

Glad I could help :)

This code works perfectly but it also displays the name of the categories on the top of the post in the front end which is not needed at all. How to modify this code so that it just adds the category name to the body class on single posts but does not display the name of the categories in the front end?

Try this snippet:

add_filter('body_class','add_category_to_single');
  function add_category_to_single($classes) {
    if (is_single() ) {
      global $post;
      foreach((get_the_category($post->ID)) as $category) {
        // add category slug to the $classes array
        $classes[] = 'category-' . $category->category_nicename;
      }
    }
    // return the $classes array
    return $classes;
}

Hi! I tried the snippet with adding categories to single post body classes. Works great. Would it be possible also to do this with tags?

Let's say I would like to give different styles of the mobile head (with css) on single posts based on a tag. All posts with 'Orange' tag gives them orange head when viewing them as single posts. 'Yellow' tag gives them yellow head etc.

And if possible I would like to use the same css class on an archive page or the blog page.

Hi there,

for Tags you would use this:

add_filter( 'body_class', 'add_tags_to_body_class' );
function add_tags_to_body_class( $classes ) {

    if( is_single() && $tags = get_the_tags( get_queried_object_id() ) ) {
        foreach( $tags as $tag ) {
            $classes[] = 'tag-' . $tag->name;
        }
    }
    return $classes;
}

Archive pages automatically add the tog-term class to the body.
But the blog itself does not - so i am not sure what you require there.

Hi David.
Thanks. Works perfect.

You're welcome

This archived topic is closed to new replies.