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' );
1 Star2 Stars3 Stars4 Stars5 Stars 4.00 (1 votes)

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

p.s. I increased my AdSense revenue by 68% using AI 🤖. Read my Ezoic review to find out how.

Leave a Reply

avatar
  Subscribe  
Notify of