Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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);
    $exploded=array_filter($exploded);
    return implode(' ', $exploded); 
}
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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