Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save elias1435/d1f86768b8f8ac6104c1f0f02dfac97d to your computer and use it in GitHub Desktop.
Save elias1435/d1f86768b8f8ac6104c1f0f02dfac97d to your computer and use it in GitHub Desktop.
How to Add Category Id to WordPress Body and Post Class This snippet is very handy if you wish to add category ID to WordPress body and post class for ex. targeting CSS styles and such.
function category_id_class($classes) {
global $post;
foreach((get_the_category($post->ID)) as $category)
$classes [] = 'cat-' . $category->cat_ID . '-id';
//if you want to add category slug replace below code
//$classes [] = 'cat-' . $category->slug;
return $classes;
}
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment