‘posts_where’ filter not applying ‘WP_Query’ in `wp_ajax`

is_search() is only true if the main query is for the search results. When you create your own query with new WP_Query, you’re not using the main query. Additionally, AJAX requests do not even have a main query, so functions like is_search(), is_archive() etc. do not work.

If you want to check if a specific query is a search, you should use the is_search() method of the query, like this:

$query->is_search();

The posts_join and posts_where filters are applied to all queries, but the callbacks to those filters receive the current query object as an argument, and you can use this to check for any search queries so that you can apply your filter:

function search_by_meta_join( $join, $query ) { // <-- Note the additional argument.
    global $wpdb;

    if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.
    }

    return $join;
}
add_filter('posts_join', 'search_by_meta_join', 10, 2 ); // <-- Note the '2' which indicates we're accepting 2 arguments.

function search_by_meta_where( $where, $query ) { // <-- Note the additional argument.
    global $wpdb;

    if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.

    }

    return $where;
}
add_filter( 'posts_where', 'search_by_meta_where', 10, 2 );// <-- Note the '2' which indicates we're accepting 2 arguments.

The same principle applies whenever you’re filtering pre_get_posts as well. You should always use the query object that’s passed to the filter to check these things, otherwise your changes will apply to all queries on the search page, including menus, widgets, and secondary queries, not just the specific search query.

Leave a Comment