WordPress Shortcode Display Search Form
Here is an easy custom WordPress function to display your theme’s search form via shortcode. This makes it easy to display the search form on any Post or Page.
WP shortcode for default search form
To display your theme’s search form via shortcode, first add the following custom function to your theme’s functions.php file:
function shapeSpace_display_search_form() {
return get_search_form(false);
}
add_shortcode('display_search_form', 'shapeSpace_display_search_form');
This simple function returns the search form using get_search_form() with the echo
parameter set to false
, so as to return the form rather than display it.
WP shortcode for custom search form
Alternately, we can define and return our own custom search form like so:
function shapeSpace_display_search_form() {
$search_form = '<form method="get" id="search-form-alt" action="'. esc_url(home_url('/')) .'">
<input type="text" name="s" id="s" placeholder="Search..">
</form>';
return $search_form;
}
add_shortcode('display_search_form', 'shapeSpace_display_search_form');
So instead of using get_search_form()
, we add our own custom form markup. This is useful when you want to display a variation of your theme’s default search form. Notice that we are using home_url() for the value of the action
attribute.
Display the search form
Once you have added the custom function to your theme’s functions.php
file, you can display the search form on any WP Post or Page by simply adding the following shortcode:
[display_search_form]
That’s all there is to it. Feel free to customize the shortcode function to suit your specific needs. Cheers :)