WordPress: Add custom class name to body for a particular template

Last updated on

To add a custom CSS class to the <body> tag in WordPress, add the following to functions.php.

In the following example, we are adding the class my_custom_class to the template my_template.php and my_other_class to the template my_other_template.php.

function my_custom_classes( $classes ) {
    if ( is_page_template( 'my_template.php' ) ) {
        $classes[] = 'my_custom_class';
    }
    if ( is_page_template( 'my_other_template.php' ) ) {
        $classes[] = 'my_other_class';
    }
    return $classes;
}
add_filter( 'body_class', 'my_custom_classes' );

Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.

Leave a reply

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