Add a login/logout link to a WordPress navigation menu

I was looking for a way to add a login/logout link to a WordPress menu a few months back and I was not able to find it a good solution anywhere, so here it is. I also summited an idea to WordPress to see if they can add the option on the admin menu area where you can select it just like you select the homepage link.

Now, there are a few posts that show you how to do it, but they over complicate things, they also ask you to use “ob_start()” function that you don’t need at all.

No plugin needed, add it to the theme’s functions.php file

Add the following code to your theme’s functions.php file and change the menu area name if you are not using “primary“. For WordPress 3.0 and up.

//Add login/logout link to naviagation menu
function add_login_out_item_to_menu( $items, $args ){

	//change theme location with your them location name
	if( is_admin() ||  $args->theme_location != 'primary' )
		return $items; 

	$redirect = ( is_home() ) ? false : get_permalink();
	if( is_user_logged_in( ) )
		$link = '<a href="' . wp_logout_url( $redirect ) . '" title="' .  __( 'Logout' ) .'">' . __( 'Logout' ) . '</a>';
	else  $link = '<a href="' . wp_login_url( $redirect  ) . '" title="' .  __( 'Login' ) .'">' . __( 'Login' ) . '</a>';

	return $items.= '<li id="log-in-out-link" class="menu-item menu-type-link">'. $link . '</li>';
}add_filter( 'wp_nav_menu_items', 'add_login_out_item_to_menu', 50, 2 );

8 Comments on “Add a login/logout link to a WordPress navigation menu

  1. Dave Woods says:

    Have been hunting around everywhere for a solution to just add a “Logout” link to the frontend without redirecting to the standard wp-admin login page. This solution did the trick so just wanted to say thanks for sharing.

  2. jaffa says:

    This didn’t work for me. I added it to my functions but I don’t see the logout link 😐

  3. Hax says:

    are you using the regular wp menus? Or is there something custom in your theme? Also be sure to change the menu location on the script: “primary”

  4. Tom says:

    I can’t figure this out. What am i suppose to put in place of PRIMARY? $args->theme_location != ‘primary’.
    Primary does not work.

  5. Hax says:

    $args->theme_location != ‘primary’ “primary” should be the name of your menu name location. for the most part it should be a lower case name.

    Location names change by theme. go to the “menus”

    menu and check the location name

  6. Tom says:

    I had to inspect the code to get the location.

    Where i have to set location to “avia”

  7. Hax says:

    In the code above. if your theme location is “avia”, change “primary” to “avia”.
    if( is_admin() || $args->theme_location != 'avia' )

    you could modify your theme but is not recommended.

Comments are closed.