06 Feb, 2009
get_search_form() in wordpress
Posted by: Jennifer In: WordPress|WordPress Hacks|WordPress Plugins
So I've discovered a new feature in WordPress 2.7 – get_search_form(). What this will do is first (for backward compatibility sake) look for a file named searchform.php in the theme directory – and if it doesn't find it then it generates the HTML for you. (=cringe=) Yeah. You just know I've gotta be overriding that.
Thankfully the function does have a filter hook. First – to understand what the function is doing – here is a link to the phpxref of the function.
So you can override this one of two ways. You can simply create a searchform.php page in your theme directory with the search form you want to use… or you can add something like the following to your functions.php file in your theme directory (or create a plugin with this, although that seems like overkill – probably a function in functions.php is fine)
function my_search_form($form) {
$form = '<form method="get" id="searchform" action="' . get_option('home') . '/" >
<div><label class="hidden" for="s">' . __('Search for:') . '</label>
<input type="text" value="' . attribute_escape(apply_filters('the_search_query', get_search_query())) . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'.attribute_escape(__('Search')).'" />
</div>
</form>';
return $form;
}
add_filter('get_search_form', 'my_search_form');
The above value of "$form" is the same HTML that WordPress' get_search_form() will spit out. And it has some nice things in it (like pre-populating the search field with the last query requested). So you can start modifying it from there as you need to (ie. removing or changing "Search for" etc.
From a performance standpoint – I'm not sure which would be better – creating the searchform.php or making use of the get_search_form filter. (or is it negligible?)