How can you filter or alter the search terms that users enter into a search field? Is there a hook available?

The idea is to use this function to filter out 2-3 letter "filler" words ("on", "and", "the", etc.)

function prepSearchStr($str){
    $str=preg_replace('©[^a-zA-Z0-9]©', ' ', $str);
    $str=preg_replace('©(?<=\s|^)(([a-zA-Z]{1,3})|[0-9]{1,2})(?=\s|$)©', ' ', $str); //remove smaller groups of characters
    $exploded=explode(' ', $str);
    return implode(' ', $exploded); 

You can use parse_query:

function wpa64292_parse_query( $query ) {
    if( isset( $query->query_vars['s'] ) && !empty( $query->query_vars['s'] ) )
        $query->set( 's', prepSearchStr( $query->query_vars['s'] ) );

add_action( 'parse_query', 'wpa64292_parse_query' );

Note that it won't alter the query string you see in the browser, but if you echo get_query_var('s') in your template you'll see it's been altered.

  • It works, but if the new query var ends up being an empty string, all posts and pages are returned. How can I prevent that? – Force Flow Sep 6 '12 at 15:27
  • As a workaround, I put a if(!empty($wp_query->query_var['s'])){} before have_posts() in the search.php template. – Force Flow Sep 6 '12 at 16:36

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.