Use is_category(), is_tag(), … in functions.php

I want to check in functions.php if actual page is a category page, tag page, … but the functions to check it (is_category(), is_tag(), …) doesn’t seem to work, as this condition:

if(is_category() || is_tag() || is_home())

never pass.

E.g. is_category() doesn’t seem to need to be called on the loop.

Any idea of why it’s not working and how to solve it?

Edit:

The complete example for my case is:

inside functions.php

/* Add hentry class to body */ 

if(! function_exists( 'one_function' )) {
    function one_function( $classes ) {
        $classes[] = get_classes(); //this is a custom theme function which put the classes into an array.
        $classes[] = 'hentry'; 

        return $classes;
    }
    if(is_category() || is_tag() || is_home())
        add_filter( 'body_class', 'one_function' );  //this is executed if removing the "if" condition

}

1 Answer
1

Your problem is that you didn’t wrap it in a callback, but executed it immediately when functions.php was loaded by core. By then the global $wp_query object isn’t initialized fully and the is_category() etc. wrappers can’t deliver what you are expecting them to do. So your if/else checks should be moved inside the callback like this:

add_filter( 'body_class', 'addBodyClasses' );
function addBodyClasses( $classes )
{
    if (
        is_category()
        || is_tag()
        || is_home()
        )
    {
        $classes = array_merge( $classes, array(
            'hentry',
            // other classes you want to add go here
        ) ); 
    }

    return $classes;
}

Leave a Comment