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)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x