How To Add A Custom Body Class To Specific Pages

Home » Blog » WordPress Development » How To Add A Custom Body Class To Specific Pages

Do you want to add a custom body class to some specific pages on your website? You can do so by adding a filter function to the body_class filter that checks if the page is your desired page and adds a custom class.

Add this code to your theme’s functions.php file or to a custom plugin:

function add_custom_body_class_to_specific_pages( $classes ) {
     if ( is_page('page-slug') || is_single('my-post-thumbnail') || is_category('my-category-slug') || is_tag('my-tag-slug') )
          $classes[] = 'my-custom-body-class';
     return $classes; 
add_filter( 'body_class', 'add_custom_body_class_to_specific_pages');

The above code adds a filter function to the body_class filter. body_class is a function that is called to get the classes for the <body> tag. Our filter function will add a custom class called ‘my-custom-body-class’. Replace it with your desired class.

The filter function first checks if the user is on the desired page. I have added examples for checking for a specific page, single post, category, and tag. Use the appropriate function by adding the slug of the desired page to it and remove the other functions.

For the above code to work, your theme needs to call the body_class function on the body tag to add CSS classes to it. If your theme doesn’t do so already, add it yourself:

<body <?php body_class() ?>>

Replace the opening body tag in your theme’s header.php file with the above code if it doesn’t already look like this.

Leave a Reply

Your email address will not be published. Required fields are marked *

Register an account to save your snippets or go Pro to get more features.