Add Login / Logout Link to wp_nav_menu Dynamically

Thank you so much to Chittaranjan for posting this on Stackexchange…

This function targets wp_nav_menu by it’s theme_location, and dynamically adds a Login / Logout button to it, including nonce.

add_filter( 'wp_nav_menu_items', 'wti_loginout_menu_link', 10, 2 );
function wti_loginout_menu_link( $items, $args ) {
   if ($args->theme_location == 'menu-1') {
      if (is_user_logged_in()) {
         $items .= '<li class="right"><a href="'. wp_logout_url() .'">'. __("Logout") .'</a></li>';
      } else {
         $items .= '<li class="right"><a href="'. wp_login_url(get_permalink()) .'">'. __("Login") .'</a></li>';
   return $items;

Classes can be added to the menu, and the text for each URL can be adjusted.

I’ve adjusted the above from the original post and included my own above, but I really didn’t change much. It basically works as-is.

Add to functions.


Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.