0

I'm trying something but I have an issue with WP_Query.

I've an Hook on the_post in order to add some variation on the query.

add_filter('the_posts', 'query_variation');

function query_variation($posts, $query = false) {
    if (is_search())
    {
    // Do stuff
    }
}

It's working well when I'm searching on the site. But, I know creating an ajax search like that :

function ajax_search_123( ){
     $search_keyword = esc_attr($_REQUEST['query']);
     $args = array(
            's'                     => $search_keyword),
            'post_type'             => 'product',
            'posts_per_page'        => 3,
        );
        $products_query = new WP_Query( $args );
        // Do stuff with $product_query
}

But when I instanciate WP_Query with $args, is_search() doesn't return true so I'm entering on the if...

What Can I do ?

Thank you for your help

1
  • It's hard to know without more context, but it sounds like you may be better served by the pre_get_posts action.
    – mrwweb
    Commented Jul 17, 2014 at 22:30

1 Answer 1

0

You are slightly confusing $wp_query global variable with WP_Query class/objects. $wp_query is an object instance of WP_Query, but not every WP_Query object has anything to do with $wp_query global.

Function version of conditionals, such as is_search(), always act on main global query. You shouldn't use them inside filters, since global state might be one thing and the query you are actually in another.

Inside hooks you should be always making checks on instance of query provided, via its methods. For example $query->is_search().

2
  • Understood, so I can't use get_search_query() but $query->get('s') instead ?
    – XciD
    Commented Jul 17, 2014 at 23:05
  • @XcID yes, and so on. Just check sources of the "global" versions of function to see which data they are wrapping and how.
    – Rarst
    Commented Jul 17, 2014 at 23:07

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.