WordPress Login / Logout menu link

WordPress logo with a Christmas hat

Almost every site I build requires WordPress login / logout functionality and I haven’t been able to find a standard way of adding a login/logout link to the primary menu of my theme.

I wrote this little filter that works like a charm and what I really really like about it is that when user hits the “logout” link, they will get redirected to the homepage rather than the standard WordPress logout page, which is wp-login.php?loggedout=true or something like that.

So here is the WordPress login / logout hook I’ve been using for quite some time:

/*------------------------------------------------*/
/* Add login/logout link to naviagation menu
/*------------------------------------------------*/
if( ! function_exists( 'add_loginout_to_menu' ) ) {
	function add_loginout_to_menu( $items, $args ){

	    //Nav location in your theme. In this case, primary nav. Adjust accordingly.
	    if( is_admin() ||  $args->theme_location != 'primary' )
	        return $items; 

	    if( is_user_logged_in( ) ) {
	        $link = '<a href="' . wp_logout_url('/index.php') . '" title="' .  __( 'Logout' ) .'">' . __( 'Logout' ) . '</a>';
	    }
	else  $link = '<a href="/loginlink" title="' .  __( 'My Account' ) .'">' . __( 'My Account' ) . '</a>';

	    return $items.= '<li id="loginout-link" class="menu-item menu-type-link">'. $link . '</li>';
	}
}
add_filter( 'wp_nav_menu_items', 'add_loginout_to_menu', 10, 2 );

Marko