How to modify posts_where filter only for the search query

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)

Topic request-filter posts-where filters Wordpress

Category Web


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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.