How do I enable search on WordPress?

Want to enable search on WordPress? For example, you want a text box on the top of the each page.

However, you don’t want to drag a widget. We can place a search widget on the top of the sidebar.

It’s the easiest way imaginable.

Moreover, it doesn’t require any coding skill.

But we want to make it other way.

Let’s try.

Does WordPress have a search function?

Yes. WordPress does have.

In other words, WordPress needs only three functions.

Take a look at this image first.

A simple search function in WordPress
A simple search function in WordPress

In the header PHP file we’ve added this WordPress function:

<p>
<?php get_search_form( ); ?>
</p>

Above all, it automatically adds the search text box. Although we’re not finished yet.

We need to add a PHP file named “search.php” and copied the entire archive PHP file code into it.

Now, we can search any word inside our WordPress site. Meanwhile it’ll give us search results.

But there is a problem.

How do I set search results in WordPress?

We cannot our search results if someone clicks the button without typing any text.

Take a look at the following image:

Problem of normal search function in WordPress
Problem of normal search function in WordPress

The empty search also gives us an output. On the other hand, we don’t want this.

We want a validation check. To do that, we need to take some extra steps.

Firstly, we need to add a PHP file named “searchform.php”.

Next, we add a simple HTML form there.

<form action="/" method="get">

<div class="form-group">

<input type="text" name="s" class="form-control" 
id="search" placeholder="Search"
value="<?php the_search_query( ); ?>"required>
</div>

<button type="submit" class="btn btn-primary">Submit</button>
</form>

How do I create a search result page?

This time the look of the search bar changes. As a result we view this search bar on the header section.

After adding search form page in WordPress
After adding search form page in WordPress

In the “search.php” file we can now add this simple WordPress function.

<h1>Search Results For <?php echo get_search_query( ); ?></h1>

What does it mean?

When you search, it also gives output of the search query. However, if someone does not type any text and clicks the button, it automatically validates.

Just like the following image.

Validating empty search query in WordPress ignoring blank space
Validating empty search query in WordPress ignoring blank space

Therefore, adding search functionality in any WordPress website is not difficult. On the other hand, it’s super simple.

What Next?

Books at Leanpub
Books in Apress
My books at Amazon
GitHub repository
Technical blog
Twitter


Posted

in

,

by

Comments

Leave a Reply