Thursday, January 30, 2014

How to Create a Search Template for Wordpress

A search page is the page that displays the results of your search query typed into the search bar. This is an intermediate tutorial, and assumes that you already know how the basics of Wordpress works.

First of all, we begin with creating the search bar on page with this small snippet of code.

<?php get_search_bar(); ?>


When we see the source code in the file produced in the browser, it appears as:

<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>



We can customise this by using the HTML that you prefer by editing the functions.php file. First of all, create the template that you would rather use, making sure that you have the basic elements of the search bar.

I decided to go with this code instead to match my template that I previously made before tinkering with Wordpress. There is not much difference, but it is good to know you can customise it.

<form role="search" method="get" class="searchform" id="searchform" action="'.home_url('/').'" ?>
<input type="text" value="'.get_search_query().'" name="s" class="search-input" id="s" />
<input type="submit" id="searchsubmit" value="'.esc_attr__('Search').'" />
</form>

Go to the functions.php file.

// Override Search Form Function

function my_search_form( $form ) {

  $form = '<form role="search" method="get" class="searchform" id="searchform" action="'.home_url('/').'" ?>'.

          '<input type="text" value="'.get_search_query().'" name="s" class="search-input" id="s" />'.

          '<input type="submit" id="searchsubmit" value="'.esc_attr__('Search').'" />'.

          '</form>';

  return $form;
}

Initialise the search form function to use the function you just created.

add_filter( 'get_search_form', 'my_search_form' );

And that should be done for the search bar. Now when you use the get_search_form(); function in the place you want it to appear in the front end, you should now get the customised version.

Now, I will talk about how to get the Search Results page working. The template file is called search.php, so create this file in your main theme directory if you haven't already.

For the basic stripped down version of the search results page, you will at least need the loop displaying the title with a link to the permalink and an excerpt of the entry.

At the beginning of the search.php page, you will need to type the Template name within PHP tags.

To be continued...

Sources
http://codex.wordpress.org/Creating_a_Search_Page
https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter

No comments:

Post a Comment