Home / body_class / Add post category to body_class on single posts
  • How to Add post category to body_class on single posts


    This little snippet will take all the categories assigned to a post and add them to the body_class “sgl-cat-{category-name}”.

    ( click code to copy )

    wordpress snippet : PHP

    	function add_category_to_single($classes, $class) {
    		if (is_single() ) {
    			global $post;
    			foreach((get_the_category($post->ID)) as $category) {
    				$classes[] = 'sgl-cat-'.$category->category_nicename;
    		return $classes;

    ( WordPress codex functions, hooks, in this snippet. )

    body_class, the_category, is_single, get_the_category, add_filter, _n,
  • Great, but you need one correction or the above code will give a fatal error. The hook should have:
    add_filter(‘body_class’,’add_category_to_single’,10,2) since you pass in 2 parameters.