WordPress Tutorial: Outputting Search Terms

Date:
Jul
21

Here is a quick fix for outputting WordPress search parameters within form fields such as search input boxes.

Just add the following snippet to your functions.php file:

function new_get_search( $escaped = true ) {
$query = urldecode(get_query_var( 's' ));
if ( $escaped ){
$query = esc_attr( $query );
}
return $query;
}
add_filter( 'get_search_query', 'new_get_search');

Then when used with a standard WordPress searchform.php file, the output is rendered in natural language without the extra query string variables. Example:

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div class="form-search">
<label for="search">Search:</label>
<input type="text" value="<?php echo get_search_query(); ?>" name="s"
id="s" size="20" onfocus="this.value=''" class="text" />
<button type="submit" title="Search" class="button"><span><span>Search</span></span></button>
</div>
</form>

So when searching for test test the search input field will display test test instead of test+test.

Comments