How to modify posts_where filter only for the search query

Problem:

The problem with your current snippet is that you are just checking the global main query object, no matter what the current query object is.

Workaround:

Note that the second input argument for the posts_where filter callback, is the current query object.

Use that to determine if it’s the main search query on the front-end with:

add_filter( 'posts_where', function ( $where, \WP_Query $q ) 
{
    if( ! is_admin() && $q->is_main_query() && $q->is_search()) // No global $wp_query here
    {
        // ... your modifications
    }

    return $where;      

}, 10, 2 ); // Note the priority 10 and number of input arguments is 2

There’s also the posts_search filter for the WHERE search part, if that’s what you need to modify.

But in general I would say only modify the generated SQL by hand if, you really must and have no other alternatives.

Leave a Comment