0

i need to exclude last letter from search string, because WP search is word sensitive.

I mean the situations like user entered word "dogs" but in titles i have no dogs, i have "dog". In this case user gets 0 results, but if we filtered search string and remove last letter, before sending search results user gets results from "dog".

Code is simple

$word = substr($word, 0, -1); 

Where $word is a search string. But i can't find a hook. Is there any filter or hook, or where is processing search string file?

0

You can use the get_search_query filter.

function mySearchFunction($search_term){

    $search_term = substr($search_term, 0, -1);

    return $search_term;

}

add_filter('get_search_query','mySearchFunction');

EDIT

Action to filter query results:

function mySearchFilterFunction($query) {

 if ( !is_admin() && $query->is_main_query() && $query->is_search) {

    $search_term = $query->get('s');
    $query->set('s', substr($search_term, 0, -1));

 }

}
add_action( 'pre_get_posts', 'mySearchFilterFunction');

get_search_query filter is not needed because it uses get_query_var( 's' ) which is modified by our pre_get_posts action.

7
  • Works not as expected, it doesn't remove last character, but doesn't display in template "Search for get_search_query()", where get_search_query() is a search string – Alex Pain Mar 27 '17 at 16:00
  • What do you mean is not working? You asked for a hook and this is the hook processing the search term. – Laxmana Mar 27 '17 at 16:05
  • @AlexPain Sorry, I didn't understood that you need to modify the search results also. I update my answer. – Laxmana Mar 27 '17 at 16:31
  • Sory, but not working. Yes, i'm looking for hook, but pre_get_posts or get_search_query don't work. I need to exclude last character before i get results – Alex Pain Mar 28 '17 at 11:52
  • Of course i can make it by jquery, but i think in this way maybe right to do it with php – Alex Pain Mar 28 '17 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.