Wordpress - Add "Logout" link to navigation menu

You can achieve this using the wp_nav_menu_items hook. Let's have a look at the following piece of code which shows the login/logout link on the primary menu location.

add_filter( 'wp_nav_menu_items', 'wti_loginout_menu_link', 10, 2 );

function wti_loginout_menu_link( $items, $args ) {
   if ($args->theme_location == 'primary') {
      if (is_user_logged_in()) {
         $items .= '<li class="right"><a href="'. wp_logout_url() .'">'. __("Log Out") .'</a></li>';
      } else {
         $items .= '<li class="right"><a href="'. wp_login_url(get_permalink()) .'">'. __("Log In") .'</a></li>';
      }
   }
   return $items;
}

This is what we have implemented in the above example.

  1. First added a filter for wp_nav_menu_items hook and attached a function to it.
  2. After checking for primary theme location, we have checked whether user is logged in or not.
  3. If logged in, we have showed the Log Out link otherwise the Log In link.
  4. We have passed the permalink of the currently viewing page to the login url so that user will be redirected to the current page after successful login.
  5. We have used the class="right" to the above code to meet your requirement.

You can find a detailed explanation on this blog.


Try adding a custom link with http://example.com/wp-login.php?action=logout It worked for me!


If you're flexible about adding a plugin to get this functionality, you could use: https://wordpress.org/plugins/login-logout-register-menu/

It simply adds a very convenient section in the menu builder. You can combine it with another plugin to restrict what menu items are shown to logged in users, which ones to logged out users, and which ones to everyone.

enter image description here

Tags:

Login

Menus