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.

2 Comments

  1. Marc on May 30, 2015 at 7:15 am

    This works fine with my primary menu but for some reason it doesn’t work with the secondary menu. I cam even get it working with a third custom menu I set up. Any ideas why the secondary wouldnt work??

  2. Dalton on May 22, 2015 at 6:20 am

    This fix isn’t working for me which I believe is due to my theme + lack of knowledge. I am using the tesseract theme and the theme has many .php documents under the > Apprerance > Editor section.

    I have tried to paste this code into both the functions.php and the header.php and both places the login button does not appear on my menu. Does which part of the .php document i paste it in matter, will it work if i paste it in a specific place?
    Please give me some suggestions as I am new to this. Thanks!

Leave a Comment