Add a login/logout link to a WordPress navigation menu

Screen Shot 2013-09-12 at 6.03.09 PM

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 );

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

  1. Haxsays:

    @ ribeiro,

    instead of using “wp_logout_url” function you can hard-code the urls in the anchor (a) tags.

  2. Haxsays:

    @vrsotto,

    you will have to change this line base on the user role.
    $redirect = ( is_home() ) ? false : get_permalink();

Comments are closed.