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?

3
  • 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
    Commented Aug 20, 2016 at 15:14
  • You are correct. I put ID as a place holder. I'm working on page ID 40 :) Commented Aug 20, 2016 at 15:22
  • The filter is working, the condition isn't and it's breaking body classes on single posts pages. Commented Aug 20, 2016 at 15:23

1 Answer 1

4

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;
}
1
  • 2
    you're welcome, I guess it's like plumming, we must keep the water flowing through the pipes ;-) @Jarmerson
    – birgire
    Commented Aug 20, 2016 at 15:40

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.