In some cases, you need to add a custom CSS class to the body tag for specific pages. For example, you might want to add a class to the pages in a certain section of your site, or only to the homepage.

To do this, you can use the body_class() function. This function outputs a list of classes for the body element. You can then use this list in your CSS to target specific pages.

For example, let’s say you want to add a class of “homepage” to the body tag on the homepage. You can do this by adding the following code to your functions.php file:

function my_body_classes( $classes ) { 
    if ( is_front_page() ) { 
        $classes[] = 'homepage'; 
    } 
    return $classes; 
} 

add_filter( 'body_class', 'my_body_classes' );

This code will check if the current page is the homepage. If it is, it will add the “homepage” class to the list of classes. You can then use this class in your CSS to target the homepage. For example:

.homepage {
    background-color: #000;
}

If you want to add the custom class to a specific page, you can check for that page with the is_page function by passing it the slug of the page:

function my_body_classes( $classes ) { 
    if ( is_page('my-page-slug') ) { 
        $classes[] = 'my-page-custom-class'; 
    } 
    return $classes; 
} 

add_filter( 'body_class', 'my_body_classes' );

You can also target specific blog posts using the is_singular function:

function my_body_classes( $classes ) { 
    if ( is_singular('my-post-slug') ) { 
        $classes[] = 'my-post-custom-class'; 
    } 
    return $classes; 
} 

add_filter( 'body_class', 'my_body_classes' );

In the same way, you can also target category and tag archive pages using the is_category and is_tag functions respectively.

Pin It on Pinterest

Share This