WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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); 
share|improve this question
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

Your Answer


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.