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

Introduction

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.

Implementation

Our search menu tab implementation involves two steps:

Create a Custom Links tab for search.

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.

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:

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.