WordPress

Display A WordPress Search Form

Wordpress has an built in search facility which will allow you to search for keywords within your posts search in either the post title or the post content.

In order for WordPress to perform a search on your posts and return the search results page it will need to have a $_GET variable of s. When WordPress finds this query string parameter it will perform a search on the value of this parameter.

You can't ask your users to type in a query string of ?s=search%20wordpress whenever they want to search for something so you need to provide them with a search form, where they can type in the keywords, hit search and we will return a list of posts for them to choose from.

Default WordPress Search Form

To display a search form in your WordPress theme you can use something similar to this.

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
    <div><label class="screen-reader-text" for="s">Search for:</label>
        <input type="text" value="" name="s" id="s" />
        <input type="submit" id="searchsubmit" value="Search" />
    </div>
</form>

But if you want to include this in multiple places on your theme you don't want to copy this mark-up everywhere, as in the future if you want to change the text on the search button you will have to do it in all the places this mark-up exists.

Display Search Form On Theme

Wordpress comes with a built in function to display the search form on your WordPress theme.

<?php get_search_form( $echo ); ?>

Placing this in your theme will display the default WordPress search form which is the same as above. You can override this default search form with your own by adding a theme file named searchform.php. WordPress will first search for a file named searchform.php, if it can't be found then it will return the default search form.

Create Search Form Shortcode

If you want the content authors to be able to add a search form inside the posts you can create a shortcode to add this search form to the page.

Create a function inside your functions.php file to add a search form to the page with a shortcode.

function search_form_shortcode( ) 
{
    ob_start();

    get_search_form( );

    $html = ob_get_contents();
    ob_end_clean();
        
    return $html;
}

add_shortcode('search_form', 'search_form_shortcode');
Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days