WordPress Tip — How To Manually Hook Menu Items To A Specific Menu

Wordpress 3 menu system offers the flexibility of defining the multiple menus on the go. It simply takes you a few clicks and drag and drop to create the menus. In other words, the all new integration of user interface for menu management has simplified the whole process of creating, removing and managing multiple menus. But as the things advance, they leave behind some quirks. For instance, the integrated user interface for menu management doesn’t provide either the home link or the login / logout link to be readily used in navigation menu. You can add the following code to your theme’s functions.php.


function add_login_logout_link($items, $args)
	{
	ob_start();
	wp_loginout('index.php');
	$loginoutlink = ob_get_contents();
	ob_end_clean();
	$items .= '<li>'. $loginoutlink .'</li>';
	return $items;
	}
add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);

However this introduces another glitch. When you include the menu items in this fashion, it adds the specific menu item to both, primary navigation menu as well as secondary navigation. If you want to restrict the inclusion of menu items to only one menu, secondary navigation menu for instance, replace the filter wp_nav_menu_items with wp_nav_menu_secondary_items. Note the slug of the menu has been inserted which helps this filter to be menu specific (the menu named “secondary” in this case). Thus the complete code now becomes:


function add_login_logout_link($items, $args)
	{
	ob_start();
	wp_loginout('index.php');
	$loginoutlink = ob_get_contents();
	ob_end_clean();
	$items .= '<li>'. $loginoutlink .'</li>';
	return $items;
	}
add_filter('wp_nav_menu_secondary_items', 'add_login_logout_link', 10, 2);

All the best for coding!

Divi WordPress Theme