How to modify posts_where filter only for the search query

The question:

I’m using posts_where filter in order to modify the user searches on a web, but i find out that some default widgets like the “more recent posts” uses this filter too and their behaviour are also modified.
I am trying to find a way to avoid that anything other than the users searches use the posts_where filter.

This is my code:

add_filter( 'posts_where' , 'posts_where_statement' );

function posts_where_statement( $where ) {
   global $wp_query;
   global $expp;
   global $wpdb;
   $local_db = $wpdb->prefix."posts";
   $front_page_id = get_option('page_on_front');

   if ( ('page' != get_option('show_on_front') || $front_page_id != $wp_query->query_vars['page_id']) && (!($wp_query->is_search)) )
       return $where;

   //some $where modifications

   remove_all_actions ( '__after_loop');
   return $where;
}

Is there any other function or a way to make this hook/filter only work with the search query? (the one that fetches the results from the user input)

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment