Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How can I add a link to the primary navigation menu with the class="right" attribute?

I tried to add a static link to example.com/wp-logout.php?action=logout but that leads to a logout confirmation page. Is there any way to make it a log out link?

share|improve this question
1  
Have you seen existing questions and answers like this one? –  toscho Jul 29 at 19:04
    
Have you seen wp_loginout()? –  kaiser Jul 30 at 16:18
1  
I have removed the accepted answer, because it was plagiarized from this site without attribution. –  toscho Jul 30 at 23:13
    
I ended up using something similar; at least using the loginout() function. I'll post exactly what I did next time I'm in front of my computer. Thanks @toscho –  Zach Russell Jul 31 at 2:30

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.