Best Way To Add Body Class In WP

Quick Summary

  • Pass an array of class names to body_class() inside the body tag in header.php to add them alongside WordPress's own classes.
  • To remove a default class, filter body_class in functions.php, find it with array_search() and unset it from the array.
  • If the class is missing, array_search() returns false, which removes the first class instead, so check the result before unset().

body_class() prints the class attribute of the <body> tag, filled with classes WordPress generates for the current page, such as home, single or logged-in. You can add your own body classes to that list or remove ones you don’t want, which is handy for page-specific CSS, such as moving a fixed header below the admin toolbar.

Add your own classes

In your theme’s header.php, find the <body> tag and pass an array of class names to body_class():

PHP
<?php body_class(array("first_class","second_class","third_class"));?>

The call sits inside the tag itself: <body <?php body_class( ... ); ?>>. WordPress then adds first_class, second_class and third_class to its own classes on every page that uses this header. For a single class, you can also pass a plain string.

Remove a default class

To take a class away, filter the list in functions.php:

PHP
function themename_body_class($classes){
unset($classes[array_search("add_class_name_you_want_to_remove",$classes)]);
return $classes;
}
add_filter("body_class","themename_body_class");
  • The body_class filter passes all classes as an array. array_search() finds the position of the class you name, unset() removes it, and the function returns the rest.
  • Replace add_class_name_you_want_to_remove with the class, for example home.
  • If the class isn’t in the list, array_search() returns false, which PHP treats as index 0, so the first class in the array is removed instead. When the class isn’t present on every page, check the result before calling unset().
  • The same filter can add classes too: append them to $classes before returning it. That’s useful when you can’t edit header.php.
Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More