How to add Login/Logout Link to an existing menu in WordPress

Adding 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', 'codeithub_login_logout_link', 10, 2 );

function codeithub_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.

See also  Move Email Field to Top on Checkout Page

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

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

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

	
function codeithub_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.

See also  Show Custom Short Description When Empty

Leave a Reply