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 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:
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_classfilter 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_removewith the class, for examplehome. - If the class isn’t in the list,
array_search()returnsfalse, 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 callingunset(). - The same filter can add classes too: append them to
$classesbefore returning it. That’s useful when you can’t editheader.php.
Related articles
- styling the current menu item with CSS: another class WordPress adds for you to style
- splitting functions.php into smaller files: a tidy home for filters like this one

