Always use ‘get_search_form’ to create search forms

WordPress provides a lot of filters (and actions) to allow plugins or themes to modify the WordPress comportment. Among them, ‘get_search_form’ can be used to modify the search form.

If a theme author codes a search form which does not pass through this filter, no plugin is aware of this search form and thus no plugin can modify it for its own purposes. Polylang uses this filter to pass the language as parameter of the search query. This allows the search results to be only in one language. A search form which does not pass the ‘get_search_form’ filter may result in unfiltered content (potentially in all languages) or even an error 404.

So, how to do? As in most cases, everything is well explained in the Developer doc.

The first step is to use the template tag ‘get_search_form’ in the place(s) where you want to display your search form. It’s as easy as:

<?php get_search_form(); ?>

It is important to use this function as it is responsible for applying the ‘get_search_form’ filter thus informing WordPress and all plugins of the existence of your search form.

You can stop here as WordPress provides a default search form. But you may decide for a customized one. In that case, you have basically two ways. The easiest is probably to output your search form in a file called ‘searchform.php’. Here is an example taken from Twenty Eleven:

<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label for="s" class="assistive-text"><?php _e( 'Search', 'twentyeleven' ); ?></label>
<input type="text" class="field" name="s" id="s" placeholder="<?php esc_attr_e( 'Search', 'twentyeleven' ); ?>" />
<input type="submit" class="submit" name="submit" id="searchsubmit" value="<?php esc_attr_e( 'Search', 'twentyeleven' ); ?>" />

But the Codex also proposes a method which uses the ‘get_search_form’ filter itself.

add_filter(‘get_search_form’, ‘my_search_form’);
function my_search_form($html) {
 $html = … // here you can either customize the WordPress builtin search form or totally overwrite it
 return $html;

Note that the search widget will automatically use the customized search form provided by the theme.

So don’t forget. Always call ‘get_search_form’.

Picture illustrating the article by Noël Bauza and licensed under CC0 Public Domain.