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