Add Login and Logout to Your WordPress Menu

If you’ve been developing or designing sites for any length of time, I’m sure you’ve run into the scenario where you are asked to add a Login/Logout item to the menu. Often times this item is on a sub-menu, whether in the upper right corner, or footer, is dynamic where if someone is not logged into the website will display “Login” and they can click on it to login. If they are logged in, then it’ll display “Logged Out” and if clicked on, it will log them out. Pretty simple and self-explanatory functionality. But within the Menu building of the WordPress Admin we can’t accomplish such dynamic functionality. By adding a function to the functions.php file, we can accomplish this by using the wp_nav_menu_items hook.

Add the item to the Custom Menu

The wp_nav_menu_items hook allows us to add additional items to any Custom Menu that we’ve defined in the WordPress site. In the following example I’m attaching the Login/Logout item to one menu that is called ‘header_nav’.
[php]
function rezzz_add_loginout_navitem($items, $args ) {
if( $args->theme_location == ‘header_nav’ ) {
if ( !(is_user_logged_in()) ) {
$login_item = ‘<li class="nav-login"><a href="/login">Log In</a></li>’;
}
else {
$login_item = ‘<li class="nav-login">’.wp_loginout($_SERVER[‘REQUEST_URI’], false).'</li>’;
}
$items .= $login_item;
}
return $items;
}

add_filter(‘wp_nav_menu_items’, ‘rezzz_add_loginout_navitem’, 10, 2);
[/php]

The first check is to make sure we are looking for the proper menu. Then once we have that menu, check whether or not the user is logged in and display the proper link.

Search, Protected Pages, Oh My!

The wp_nav_menu_items hook can be used in a number of ways from this use case, or adding a search, protected pages that only appear under certain scenarios, etc. This hook has helped me in a number of ways and seems to be a bit over looked sometimes in favor of a plugin. As you can see, with a few lines of code, you can save yourself depending on a plugin.

photo by Robert Hurd

/ Jason Resnick

Jason is a WordPress developer helping small businesses, design and marketing agencies achieve their goals by specializing in Ecommerce and increasing conversions. Learn more about him here.

More Posts | Twitter | Work ON Your Business Challenge | Coaching

4 responses to “Add Login and Logout to Your WordPress Menu

Leave a Comment

Your email address will not be published. Required fields are marked *