Question

I'm trying to style something unique to the Blog/Posts page, which isn't on the front page. The body tag right now looks like this:<body <?php body_class() ?>>
But doing this <body <?php body_class('blog') ?>> only returns <body class="logged-in"> or just <body> if I'm not logged in.

I've tried:

<body <?php if ( is_home()) {
    echo 'class="blog"';
} else {
    body_class(); }?>>

It sort of works but it replaces the "logged-in" class entirely. There has to be a way to append classes to the body tag for posts pages right?

Was it helpful?

Solution

In your theme's functions file, use the body_class filter to add new classes:

function wpse_282694_body_class( $classes ) {
    if ( is_home() ) {
        $classes[] = 'blog';
    }

    return $classes;
}
add_filter( 'body_class', 'wpse_282694_body_class' );

If your category archives, tag archives, date archives and search results also need the same styling, which is fairly commin, check for each of them like so:

if ( is_home() || is_date() || is_tag() || is_category() || is_search() ) {}

Note that I didn't use is_archive(), because that would also affect any custom post types you might be using.

OTHER TIPS

You can pass your class as argument

<body <?php if ( is_home()) { body_class('my-class'); } else { body_class(); }?>>
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top