WP snippets: Adding an extra class to the opening body tag

With the Gutenberg Editor landed in WordPress 5.0 customizing posts and pages has become a breeze. Although sometimes it’s still necessary to add CSS applied to a larger group of pages like for a specific language or category. Below you see a few snippets that adds extra classes to the body tag so specific CSS rules for these criteria can be applied.

I will update this space whenever I find more useful snippets.

Add the page slug

/**
 * Add the page slug as a class to the body tag 
 */ 
function add_slug_body_class($classes) {
global $post;
if ( isset( $post ) ) {
$classes[] = $post->post_type . '-' . $post->post_name;
}
return $classes;
}
add_filter( 'body_class', 'add_slug_body_class' );

Add the page language

/**
 * Add a class for the selected language
*/
function add_language_body_class($classes){
$classes[] = 'language-'.ICL_LANGUAGE_CODE; 
return $classes;
}
add_filter('body_class', 'add_language_body_class');

Add the post category


function add_category_body_class($classes) {
  if (is_single() ) {
    global $post;
    foreach((get_the_category($post->ID)) as $category) {
      $classes[] = $category->category_nicename;
    }
  }
  return $classes;
}
add_filter('body_class','add_category_body_class');

Source: CSS Tricks