The login/logout functions in WordPress are great, but what if you don’t want to have to use a sidebar widget to login/out? My latest website didn’t even HAVE a sidebar, but I still wanted to make sure the login/logout was prominently displayed. The code below will allow you to add a button to your menus (code below shows option to include on all menus, or just the “primary” menu) that shows “Log In/Register” for users who aren’t currently logged in, and then switch to a “Log Out” button when they are:
In functions.php (anywhere, but I put it at the end), add the following:
1 2 3 4 5 6 7 8 9 10 11 | /************* Log In/Register and Log Out in Menu ****************/ add_filter( 'wp_nav_menu_items', 'rkk_add_auth_links', 10 , 2 ); function rkk_add_auth_links( $items, $args ) { if ( is_user_logged_in() ) { $items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>'; } elseif ( !is_user_logged_in() ) { $items .= '<li><a href="'. site_url('wp-login.php') .'">Log In/Register</a></li>'; } return $items; } |
To have the buttons show up on the Primary menu ONLY, replace both:
1 | if ( is_user_logged_in() ) { |
sections with:
1 | if ( is_user_logged_in() && $args->theme_location == 'primary') { |
If you’d rather have different buttons for the Log in, Register, Lost Password and Log Out pages, use the following code instead:
1 2 3 4 5 6 7 8 9 10 11 12 13 | /************* Login, Register, Lost Password, and Log Out in Menu****************/ add_filter( 'wp_nav_menu_items', 'rkk_add_auth_links', 10 , 2 ); function rkk_add_auth_links( $items, $args ) { if ( is_user_logged_in() ) { $items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>'; } elseif ( !is_user_logged_in() ) { $items .= '<li><a href="'. site_url('wp-login.php') .'">Log In/Register</a></li>'; $items .= '<li><a href="'. site_url('wp-login.php?action=register') .'">Register</a></li>'; $items .= '<li><a href="'. site_url('wp-login.php?action=lostpassword') .'">Lost Password</a></li>'; } return $items; } |
1 comment
Can you explain how to use a dropdown menus to show register and lost password