[Tutorial #26] Search in WordPress 2: Search Menu Tab

[Tutorial #26] Search in WordPress 2: Search Menu Tab


In last tutorial we created the search form as modal and the search result page. Now we need a way to invoke the search form.

On ModernBlackHand we invoke the search form through a menu tab, as the header menu is always present in every page. We further use some JavaScript to change the “search” text into Font Awesome’s search icon.


Our search menu tab implementation involves two steps:

  1. Create a Custom Links tab for search.
  2. Add JavaScript function to modify search tab appearance and action.

The main reason we need #2 is because wordpress does not allow emptied name tab (as we want to use a search icon). Also we prefer to specify most of the HTML attributes in the theme rather than in the admin panel, as it makes reusing theme harder.

Custom Link Search Tab

Go to Appearance -> Menus and select the header menu. At the left column open Custom Links drop-down.

Input url as http://#  for the modal and Link Text as “Search”. Add it to the menu.

wp tutotial custom link tab

Custom Links menu tab.

Once the tab is added we need a way to identify it for JavaScript. Using wordpress’ auto-assigned class is not good, as if we remove and re-add the tab the class name will change. Thus we add our own class menu-item-search  by opening the drop-down and add it inside the CSS Classes tab:

wp menu tab css

Adding our CSS class for identification.

JavaScript Codes

The code segment in our JS file assets/js/main.js is as follows. You can also find the file on my Github.

Wordpress renders the header tab via a list item <li class="menu-item-search ..."> tag and put a link tag <a> tag inside, so for the jQuery selector in line 4 we get the <a> tag accordingly.

We then go through each <a> tag element and:

  1. Remove its text (line 6).
  2. Add Font Awesome search icon classes (line 8).
  3. Add modal classes linking to the search form (line 10).

Search Pages

It’s time to see how our search pages look:

wp search menu tab

Search menu tab.

wp search form

Popup search tab.

wp search results

Search result page.

404 Not Found Template

To close this tutorial, we customize 404.php  template that is shown when the url is not found. The codes are as follows (the file can be found on my Github):

The structure is very simple, with a centered Bootstrap column (line 16) showing two <h1> header tags and an image.