Search Toggle

Adds a search icon to the primary menu. When clicked, the search form appears. If you click the search icon without entering a search term, the form closes rather than submits.

/**
 * Primary Menu Extras
 *
 */
function ea_primary_menu_extras( $menu, $args ) {
    if( 'primary' == $args->theme_location )
      $menu .= '<li class="menu-item search"><a href="#" class="search-toggle"><i class="icon-search"></i></a>' . get_search_form( false ) . '</li>';
    return $menu;
}
add_filter( 'wp_nav_menu_items', 'ea_primary_menu_extras', 10, 2 );
jQuery(function($){

	// Search toggle
	$('.nav-primary .search-toggle').click(function(e){
		e.preventDefault();
		$(this).parent().toggleClass('active').find('input[type="search"]').focus();
	});
	$('.search-submit').click(function(e){
		if( $(this).parent().find('.search-field').val() == '' ) {
			e.preventDefault();
			$(this).parent().parent().removeClass('active');
		}

	});
});
.nav-menu {
  .search-form {
		display: none;
		position: absolute;
		top: 16px;
		right: 0;
		width: 100%;

		input[type="search"] {
			background: $white;
			border: 1px solid $grey-4;
			font-size: 16px;
			line-height: 1.2;
			padding: 6px 20px 6px 8px;
		}

		@include placeholder-color( $grey-4 );

		.search-submit {
			border: none;
			color: $highlight;
			padding: 8px;
			position: absolute;
			top: 0;
			right: 0;

			&:hover {
				background: transparent;
				color: $green-2;
				outline: none;
			}
		}
	}

	&.active .search-form {
		display: block;
	}
}

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk