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

Affiliate Disclosure

Some articles may contain affiliate links. This means I receive a small commission when you make a purchase through one of these links. However I will never recommend products that I do not support.

This site uses functional cookies. More information

Deze site is standaard ingesteld op 'cookies toestaan", om je de beste mogelijke blader ervaring te geven. Als je deze site blijft gebruiken zonder je cookie instellingen te wijzigen, of als je klikt op "Accepteren" hieronder, dan geef je toestemming voor het gebruik van Cookies.

Sluiten