If you are like me, you may use a framework or theme that supports multiple menu locations. In a previous post, I discussed how to add a login or logout menu item based on menu location. However, if you use the custom menu widget, this tutorial won't help you.
Also, if you are like me, you may want to be able to customize the Log In or Log Out to Sign In or Sign Out. So to add a customized log in or log out menu item at the end of the menu, add this to your functions.php:
[php]
add_filter('wp_nav_menu_items', 'wps_add_login_logout_link', 10, 2);
function wps_add_login_logout_link($items, $args) {
$login = __('Sign in');
$logout = __('Sign out');
//use one of the following methods of identification
$menu_id = '34';
$menu_name = ''; //name you gave to the menu
$menu_slug = ''; //slug of the menu, generally menu_name reduced to lowercase
if ( ! is_user_logged_in() )
$link = '<a href="' . esc_url( wp_login_url($redirect) ) . '">' . $login . '</a>';
else
$link = '<a href="' . esc_url( wp_logout_url($redirect) ) . '">' . $logout . '</a>';
if ( ($menu_id) && ($args->menu->term_id == $menu_id) )
$items .= '<li>'. $link .'</li>';
elseif ( ($menu_name) && ($args->menu->name == $menu_name) )
$items .= '<li>'. $link .'</li>';
elseif ( ($menu_slug) && ($args->menu->slug == $menu_slug) )
$items .= '<li>'. $link .'</li>';
return $items;
}
[/php]
Bruce says
Nice tip! I’m adding that to my bag o’ tricks…
Dave Clements says
You really would think that adding a simple Logout link to a menu would be much simpler than this! Thanks for sharing this, it’s invaluable.
Maurice says
I’ve been search for a long time to find this. The other sites I’ve come across have seek only to provide a solution for a registered menu with a predefined location. Your example is exactly what I’m looking for as it applies to any menu created. As such it got added immediately. Thanks for the share.
RW says
Great resource thanks! I’m trying to add this to 2 menus BUT NOT my main or primary nav menu. Do you know how I can do this?
Thanks,
Bob
Bobby says
Worked perfect
Jason says
Is there a way to specify the position for the link? I would like this to be the 2nd item in the menu. See in the example below, how can I place this link in this spot?
Current Menu: Home | | About | Contact Us
Havilah says
Hello, does this work with the other post or independently? That is do I have to use the function.php code from the other post referenced together with this? Thanks in advance.