Skip to content

Instantly share code, notes, and snippets.

@timotheemoulin
Last active November 24, 2020 18:04
Show Gist options
  • Save timotheemoulin/edabf6725ab6a0866ecb169eb03a909d to your computer and use it in GitHub Desktop.
Save timotheemoulin/edabf6725ab6a0866ecb169eb03a909d to your computer and use it in GitHub Desktop.
[WP] Add the page/post categories in the body classes
<?php
/**
* Add the post/page categories in the body class list.
*
* @param string[] $classes An array of body class names.
*
* @return array
*/
function timwp_add_category_name_to_body_classes( array $classes ): array {
$post = get_post();
foreach ( ( get_the_category( $post->ID ) ) as $category ) {
// add category slug to the $classes array
$classes[] = 'cat-' . $category->category_nicename;
$classes[] = 'cat-id-' . $category->term_id;
}
// return the $classes array
return $classes;
}
add_filter( 'body_class', 'timwp_add_category_name_to_body_classes' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment