Skip to content

Instantly share code, notes, and snippets.

@2aces
Last active January 23, 2017 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 2aces/cd0dd2da0f3452f02d444db16c87446c to your computer and use it in GitHub Desktop.
Save 2aces/cd0dd2da0f3452f02d444db16c87446c to your computer and use it in GitHub Desktop.
Add category or categories slug(s) as class(es) to a category archive or single post as answered on Stackexchange question https://wordpress.stackexchange.com/questions/253677/different-body-classes-for-each-category/253708#253708
// Adding categories name to body class on archives
add_filter('body_class','add_category_to_classes');
function add_category_to_classes( $classes ) {
if ( is_single() ) {
global $post;
// assigns post it to variable to avoid reading an array for every loop iteration
// maybe a micro optmization? Guilty as charged!
$post_id = $post->ID;
foreach( ( get_the_category( $post_id ) ) as $category ) {
// add category slug to the $classes array
$classes[] = $category->category_nicename;
$classes[] = $category->category_nicename . '_index';
}
}
// check if in category
else if ( is_category() ) {
// get the queried object, in this case, a category object, and assigns to a variable
// see https://codex.wordpress.org/Function_Reference/get_queried_object
$category_object = get_queried_object();
// get the slug
$classes[] = $category_object->slug;
$classes[] = $category_object->slug . '_index';
}
else {
$classes[] = 'index';
}
// return the $classes array
return $classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment