? The Snippet:
function add_body_classes( $classes ) {
// Adds a class if post type is Book
if ( is_singular('book') ) {
$classes[] = 'book-single';
}
// Add a class if is not Home Page
if ( ! is_home() ) {
$classes[] = 'not-home';
}
// Add a class if user is Admin
if ( current_user_can('administrator) ) {
$classes[] = 'user-is-admin';
}
return $classes;
}
add_filter( 'body_class', 'add_body_classes' );
ℹ️ About the Snippet
In WordPress, there are a series of different classes that can be found in the body tag of the website. The class in body tag can be helpful for different styling of different sections. We can add classes based on different conditions and different pages. The snippet mentioned above is showing examples of three different classes based on three different conditions.
The first class “book-single” is being added into the body when the single page of post type “book” is opened.
if ( is_singular('book') ) {
$classes[] = 'book-single';
}
The second condition is adding a class “not-home” if any other page except Homepage is opened.
if ( ! is_home() ) {
$classes[] = 'not-home';
}
The third condition is adding a class of “user-is-admin” if an administrator user is logged in.
if ( current_user_can('administrator) ) {
$classes[] = 'user-is-admin';
}
✅ How to use the Snippet
If you want to add a single class to the body in all scenarios, you can use the snippet without any condition. Although, but if you want to add a class in some specific scenario. Then, you’ll have to use the relevant condition.
Based on your needs, below are the steps to add any class to your WordPress website:
- Open the active theme’s directory
If you’re on localhost, then you can open the directory in any code editor/IDE. If you’re working on a live site then you can go to Appearance -> Editor.
- Open functions.php and add the snippet
In your themes files, open the functions.php and somewhere in the bottom paste the code snippet after modifying as per your needs.
Note: We highly recommend you to take the backup of your theme files before editing even if you’re a WordPress developer.