Format Non-JavaScript Search Results
Learn to create the template file that shows the search results.
The search results page is powered by a file search.php
. If it is not found, then index.php
is used to display the page.
Create the file search.php
in the theme folder and write a test message like Hello from the search results page. If we refresh the search results page (or perform a search using the form on the Search page and click submit), we should be able to see this message.
For the search results page, copy the contents of index.php
into search.php
and then customize the code to display search results differently.
Page title
The title of the page is Search Results. The description is Results for "xyz", where "xyz" is the actual search string from the form.
<?phpget_header();displayPageBanner( array('title' => 'Search Results','description' => 'Results for "xyz"'));?>
For the quotation marks surrounding the search string, we can also use the HTML codes
“
and”
like'Results for “xyz”'
get_search_query()
WordPress offers a function get_search_query
to retrieve the contents of the search query variable. We will use this function to replace the hard coded xyz.
<?phpdisplayPageBanner( array('title' => 'Search Results','description' => 'Results for “'.get_search_query().'”'));?>
The get_search_query()
function converts user text to a string thereby averting execution of malicious scripts being used as the search term.
Displaying results by post type
Since we are using the code from index.php
file, the results are shown as blog posts. We want a different formatting where results are grouped based on the post type. The results for teacher posts should have a thumbnail and those of the event posts should display the date prominently. We will use conditional logic to display the results differently based on their posts ...