Append Search Form To Menu

Often there are times when I want to append a search form to a menu. This site is an example of where I did just this.

Let me start with showing you what I want to accomplish:

Function

All it takes is a simple function. Add a filter to functions.php or the file where your theme adds functions.

if ( ! function_exists( 'your_domain_add_search_form' ) ) {
	/**
	 * Appends search form to primary menu.
	 *
	 * @param string   $items The HTML list content for the menu items.
	 * @param stdClass $args An object containing wp_nav_menu() arguments.
	 * @return string returns string with search-form added.
	 */
	function your_domain_add_search_form( $items, $args ) {
		if ( 'primary' === $args->theme_location ) {
			$form = get_search_form( false );
			$items .= '<li class="search">' . $form . '</li>';
		}
		return $items;
	}
	add_filter( 'wp_nav_menu_items', 'your_domain_add_search_form', 10, 2 );
}

This function appends the search form to the primary menu. Enter the menu you need. Also remember to change the your_domain bits with your theme’s real domain name.

That’s all it takes. I hope you can find a use for this somewhere. Thanks for visiting.

Arnold.

Start the Conversation

Your e-mail address will not be published. Required fields are marked *


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.