2

I've created a function to add a class to the body, however if should only apply to a single page ID. This normally wouldn't be a problem, but it is breaking the layout for other pages.

Filter Function

add_filter('body_class','add_blog_to_body_class');

function add_blog_to_body_class($classes) {
    $classes[] = 'blog';
        return $classes;
}

My Condition (that isn't working)

function add_blog_to_body_class($classes) {
    $classes[] = 'blog';
    if ( is_page('ID') ) {
        return $classes;
    }
}

I've wrapped the entire function, the declaration, the add_filter hook, and everything without luck.

How can I have this function work on a single page ID?

  • I trust 'ID' in the condition is actually a page slug or so? And if the condition is not met, your filter is not returning anything. – cjbj Aug 20 '16 at 15:14
  • You are correct. I put ID as a place holder. I'm working on page ID 40 :) – Jarmerson Aug 20 '16 at 15:22
  • The filter is working, the condition isn't and it's breaking body classes on single posts pages. – Jarmerson Aug 20 '16 at 15:23
3

It's important to always return the value in filter callbacks, otherwise it's like adding the __return_null() callback.

Here's an example that adds the blog class only to page with ID 40:

add_filter( 'body_class', 'add_blog_to_body_class' );

function add_blog_to_body_class( $classes )
{
    if ( is_page( 40 ) )
        $classes[] = 'blog';

    return $classes;
}
  • 2
    you're welcome, I guess it's like plumming, we must keep the water flowing through the pipes ;-) @Jarmerson – birgire Aug 20 '16 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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