0

Currently I have this:

if ( ($query->is_home() && $query->is_main_query()) || $query->is_archive() || $query->is_search() ) { ... }

I tried !$query->is_admin() but this didnt seem to work, is there another way to target everything but the admin area? I'm trying to exclude a category

2
  • What do u mean by target everything ? What do you want? please be specific and clear Commented Dec 22, 2015 at 1:46
  • It looks like the question's title is not in agreement with the target everything but the admin area in the question's body.
    – birgire
    Commented Dec 22, 2015 at 2:24

1 Answer 1

1

Note that there's no is_admin() method for the WP_Query class.

But the interesting part is that PHP will not complain about this:

$query->is_admin()

where $query is an instance of WP_Query.

It will just always return false.

This is the reason why (#src):

/**
 * Make private/protected methods readable for backwards compatibility.
 *
 * @since 4.0.0
 * @access public
 *
 * @param callable $name      Method to call.
 * @param array    $arguments Arguments to pass when calling.
 * @return mixed|false Return value of the callback, false otherwise.
 */
 public function __call( $name, $arguments ) {
        if ( in_array( $name, $this->compat_methods ) ) {
                return call_user_func_array( array( $this, $name ), $arguments );
        }
        return false;
}

This is from the PHP documentation:

__call() is triggered when invoking inaccessible methods in an object context.

The magic __call method, kicks in when we call the non-existent method is_admin().

I assume you're hooking into the pre_get_posts action.

We can use the is_admin() check:

add_action( 'pre_get_posts', function( \WP_Query $query )
{
    // Only on the front-end
    if( is_admin() )
        return;

    // ... your stuff here ...

} );

or we could use the is_admin public attribute of the WP_Query instance:

add_action( 'pre_get_posts', function( \WP_Query $query )
{
    // Only on the front-end
    if( $query->is_admin )
        return;

    // ... your stuff here ...

} );

where in fact it's based on the is_admin() function, in the parse_query() method (#src):

if ( is_admin() )
    $this->is_admin = true;

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.