Build a custom search form in wordpress

Posted date: Jun 24, 2022

wordpress

You have been built your theme using HTML CSS etc and now wondering how to convert your static search bar into an active fully functionally search bar in your new WordPress theme?
In this tutorial, we’ll convert a custom-made search bar which has been built using the Bulma CSS framework.

Declare your search form in functions.php after you setup your new theme.

if ( !function_exists( 'mytheme_setup' ) ) {
    /* Theme setup */
    function mytheme_setup() {
        add_theme_support( 
            'html5',
            array(
                'search-form'
            )
        );
    }
}
add_action( 'after_setup_theme', 'mytheme_setup' );

Create a new PHP file searchform.php and paste the HTML content.

Bulma by default provided a sample search code like this

<div class="field has-addons">
  <div class="control">
    <input class="input" type="text" placeholder="Find a repository">
  </div>
  <div class="control">
    <a class="button is-info">
      Search
    </a>
  </div>
</div>

However, we had to edit this a little bit and convert it to a real <form>

So the final HTML content is this

<form role="search" method="get" id="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
    <div>
        <div>
            <div>
                <div>
                    <input type="search" type="text" placeholder="Search..." value="<?php echo get_search_query() ?>" name="s">
                    <input type="hidden" value="post" name="post_type" id="post_type"/>
                </div>
                <div>
                    <input type="submit" value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>">
                    </input>
                </div>
            </div>
        </div>
    </div>
</form>

Notes

By adding this hidden input
<input type="hidden" value="post" name="post_type" id="post_type"/>
we restring search results to posts only.

In the input field, we must use name="s" to get the correct results.