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

    add-post-category-body_class-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

    <>
    	add_filter('body_class','add_category_to_single');
    	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,