Add Menu Items Before and After wp_nav_menu

This one adds a login/logout link to the wp_nav_menu, and it also adds a greeting to the front of the menu. The greeting only gets added if a user is logged in. The greeting is, “Hi there,” and the user’s name. If the user is logged in, then a “log out” link is added. If no one is logged in, then a “log in” link is added.

This function lets you affect only the menu that you specify by theme_location (theme_location is assigned when the wp_nav_menu was registered). So if you have multiple menus, but only want to add items to one menu, here it is. This example only modifies the theme location called ‘header-menu’. Edit this, on line 8, with your own theme location of the menu that you want to customize.

You can customize this to insert your own items to the the WordPress menu. In this example, $hithere on line 12 is what gets added before the regular menu items. The $newitems variable on line 15 is what’s added to the end of the menu. If you want to change the $hithere items to be visible whether logged in or not, then remove lines 10 and 14.

* Only on the specified menu, header-menu, add 'hi there' and user name, and login/logout link. 
function smart_loginout($items, $args) {

	$href = wp_loginout( get_option('siteurl'), false );

	if( $args->theme_location == 'header-menu' ) {

		if(is_user_logged_in()) {
			$user_info = get_userdata(get_current_user_id());
			$hithere = '<li class="hithere">Hi there, ' .$user_info->user_login.'</li>';

	    	$newitems = '<li>' . $href . '</li>';
                $newmenu = $hithere . $items . $newitems;
  		return $newmenu;

	} else {

		// for other menus

		return $items;


add_filter('wp_nav_menu_items', 'smart_loginout', 10, 2);

See more:


Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this: