Hello Howdy, I hope you are developing a world’s best website in WordPress and struggling to add Login and Logout links in the header and footer menu without using any plugin?

Yes??

Then you are reading a good article for development. In the premium themes, we are getting easily log in and logout link in the menu but its difficult to add them manually. While developing a custom theme, I faced the same issues and was searching on google. I found the below code, which helps me a lot in my WordPress theme development.

WordPress Login and Logout links in the menu.

 

Many developers are developing a website in WordPress and in a few cases, they need to add Login and Logout links in the header, footer, or any menu. Many times developers are using a plugin to fulfill this requirement but as a WordPress developer, I want to advise that try to avoid plugins.

I’m using the following function to add the Login and Logout links in the header.

Step 1: Copy the below code.

Copy below code and paste it into your child theme functions.php file. If you don’t have a child theme them please read our article How to create a child theme in WordPress. 

function add_login_logout_navitem($items, $args ) {

 if ( !(is_user_logged_in()) ) {
   $login_item = '<li id="menu-item-login" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="'.site_url().'/wp-login.php">Login</a></li>';
 
 }else {
     $login_item = '<li id="menu-item-logout" class="menu-item menu-item-type-post_type menu-item-object-page">'.wp_loginout($_SERVER['REQUEST_URI'], false).'</li>';
 }
 $items .= $login_item;
 return $items;
}
add_filter('wp_nav_menu_items', 'add_login_logout_navitem', 10, 2);


Step 2: Modify code as per requirement.

  1. Please review the properly and make changes as per your requirement.
  2. Change the login URL with your current login page. It will Add automatically Login and Logout links in the menu.
  3.  If you have multiple menus then check the menu name with $args and add menu condition to display Login and Logout links proper. This will add with all the menu you need to check which menu you need. Try to print $items and $args, you will get the menu details and add if condition to display the login and logout link at the particular menu.

 

Please Note: Manage your class name as per menus.

Feel free to ask any queries if you have it. If you like this post then please share it.