2

I want to add a class to the body tag to all pages EXCEPT the homepage. Right now I have.

<?php body_class('interior'); ?>

But it adds 'interior' to ALL pages including the home page.

What is the best standard way of adding a class to the body tag?

3 Answers 3

5

Try it:

<?php
$class = ! is_home() ? "interior" : "";
body_class( $class );
?>

Or this:

<?php
body_class( ! is_home() ? "interior" : "" );
?>
4
  • Thanks for your answer! however it still adds interior to the 'home' page as well.
    – breezy
    Feb 13, 2013 at 19:52
  • Oddly, worked here. Feb 13, 2013 at 20:03
  • 1
    Try it: <body <?php body_class( ! is_home() && ! is_front_page() ? "interior" : "" ); ?>> Feb 13, 2013 at 20:04
  • I adjusted my reading settings to static and have no pages selected & it worked.
    – breezy
    Feb 13, 2013 at 20:06
1

The filter body_class can be used for this.

add_filter( 'body_class', 'body_class_wpse_85793', 10, 2 );

function body_class_wpse_85793( $classes, $class )
{
    // This one overrides all original classes
    if( is_home() )
        $classes = array( 'interior' );

    // This one simply adds a new class
    //if( is_home() )
    //  $classes[] = 'interior';

    return $classes;
}
1
  • very nice. One more reason not to copy header.php down into my child template directory if I don't need to make additional modifications to the file.
    – klewis
    Oct 16, 2017 at 15:59
1

Please use the body_class filter to add any class to the body tag in WordPress.

Add the below code to your functions.php file.

Add class to the body tag for all the pages.

    add_filter('body_class', 'wp_body_class');
function wp_body_class($class)
{
  $class[] = 'my-custom-class'; // Add your class name here. Multiple class names can be added 'classname1 classname2'.
  return $class;
}

Exclude Home Page

if (!is_front_page() ) { // exclude home or any other page.
add_filter('body_class', 'wp_body_class');
}

function wp_body_class($class)
{
  $class[] = 'my-custom-class'; // Add your class name here. Multiple class names can be added 'classname1 classname2'.
  return $class;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.