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

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;
}
add_filter( 'wp_nav_menu_items', 'themeprefix_login_logout_link', 10, 2 );

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

If using a plugin like S2 Member change the value of ‘index.php’.

theme-menu-locations

The key thing is the theme location value needs to be set  – normally themes will have primary and secondary and maybe tertiary menus.

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

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