WordPress provides many awesome ways to create websites. It’s famous because of it’s flexible features, and due to large number of plugins available. I really like the built-in WordPress Menu feature. It’s flexible and allows editing the menus or ordering by simple drag & drop.

The menu manager allows you to add pages, categories etc from the WordPress and you can also add any external link. But sometimes you just want to show / hide links based on some logic. One such example is, a registered user should see a different navigation than a normal user. We are going to discuss this today and I will show how you can add Login / Logout link at the end of the WordPress generated menus, based on the User’s Session.

We are going to use WordPress filter called wp_nav_menu_items and append the Login or Logout link at the end of the menu items based on the user session. The following function does exactly the same, what I just said above –

function add_login_logout_link($items, $args) {
 if (is_user_logged_in()) {
  $newmenu = '<li class="last"><a title="Logout" href="' . wp_logout_url() . '">Logout</a>' . $args->after . '</li>';
  $newmenu = $items . $newmenu;
 else {
  $newmenu = '<li class="last"><a title="Login" href="' . wp_login_url() . '">Login</a>' . $args->after . '</li>';
  $newmenu = $items . $newmenu;
  return $newmenu;
add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2); //hook the function

The code is pretty simple to understand, we utilize the inbuilt function called is_user_logged_in() to check if the user is logged in as a user or no. Using which we display the login / logout link. Based on your requirement you can either prepend or append the new menu items. I hope this method will help you save some time. Do write in comments if you need any sort of help with this.

Stay Digified!!
Sachin Khosla

Share this post: