We learned how to use add_filter to hook a function or a method to a specific filter action.
We also learned to use applt_filters to call the functions that have been added to the filter hook.
Finally, we learned to modify navigation menus. In this post, we are going to use the same hook function to modify the menu and create the toggle effect.
Let’s use the same examples code to add the search icon in the menus.
WordPress function.php code
add_filter('wp_nav_menu_items', 'add_search_in_menu', 10, 2);
function add_search_in_menu($items, $args) {
if( $args->theme_location == 'primary' )
$items .= ' '. get_search_form(false) .' ';
return $items;
}
You can change the menu id and replace it with your WP menu id.
Style the form and icon
Note: This style is based on other elements in the menus as well as above and below the menus. Style your elements accordingly.
.search-form{
display: none;
width: 100%;
position: absolute;
right: 0;
top: 100%;
z-index: 9999;
background: #fff;
}
.search-form input[type="search"] {
width: 90%;
height: 35px;
padding-left: 3%;
background: #d41242;
border: none;
border-left: 3px solid white;
color: rgb(231, 230, 230);
}
.search-form input[type="submit"] {
border: 1px solid white;
padding: 11px 12px;
border-radius: 0px !important;
}
.search-icon{
background-image: url('your-icon-path');
background-repeat: no-repeat;
background-position: center;
background-color: transparent;
background-size: 15px;
}
As you have noticed in the style above, we have the form display property set as none to hide the form initially. We will use jQuery to toggle the form.
jQuery
jQuery has .slideToggle() function. We are going to use it to show and hide Read more about it here.
jQuery(document).ready(function($) {
$(".search-icon").click(function() {
$(".search-form").slideToggle();
});
});
Go through this post to learn how hide a DIV on clicks outside of it using jQuery.
button icon menu search toggle