Adding a Site Login/Logout Link to an existing Menu in WordPress

You can add on to the end of an existing WordPress menu a site login/logout link. The WordPress menu must be registered and have a theme location, this will not work with custom menus.

This needs to be added to your theme functions.php file

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

function themeprefix_login_logout_link( $items, $args  ) {
	if( $args->theme_location == 'primary' ) {
	        $loginoutlink = wp_loginout( 'index.php', false );
	        $items .= '<li class="menu-item">'. $loginoutlink .'</li>';
			return $items;
	    }
	    return $items;
}

If you need to style the additional menu item, just add a CSS class into the <li> tag.

You can change the default value of  ‘index.php’ to something else.

theme-menu-locations

Normally themes will have primary and secondary and maybe tertiary menus. If you are trying to target a menu that is not a theme location you can tweak the wp_nav_menu_items filter   – see this post on how to include another menu without a location.

Now if you are logged into the site the link will say logout and if you are logged in the site will say login.

login-logout-menu

 

To have different login and logout destinations you can use a conditional if(is_user_logged_in())

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

	
function themeprefix_login_logout_link( $items, $args  ) {
    
    if( is_user_logged_in()  ) {
            $loginoutlink = wp_loginout( 'index.php', false );
            $items .= '<li class="menu-item login-but">'. $loginoutlink .'</li>';
            return $items;
    }
    else {
            $loginoutlink = wp_loginout( 'members', false );
            $items .= '<li class="menu-item login-but">'. $loginoutlink .'</li>';
            return $items;
    
    }
}

So here all menus are targetted and the login and logout destinations are different depending on whether the user is logged in or not.