How to Add a Log In/Log Out Link to a Specific Custom Menu

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]

What can I do for you!?

Custom Development

We develop plugins by determining both business/functional and technical requirements, following WordPress development best practices, and using agile methodology to ensure you get the best solution.

Consulting

Have questions? Need a reliable developer to consult? Please contact us today!

Customized Theme

We can customize your theme or child theme, or create a child theme for you based on your needs while enhancing the performance of every individual attribute.

Customized Plugin

We can customize your plugins, extend plugins (e.g., Gravity Forms, Jetpack, Soliloquy) based on your needs ensuring security, performance, and positive business impact.

Comments

  1. 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.

  2. 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

  3. 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

Leave a Reply