Senior Full Stack Developer
December 2024
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Categories


Adding Login/Logout Links In WordPress Theme Navigation

MubashirMubashir

Some time while building your WordPress theme navigation you want to show/hide certain menu items based on user state. For example you want to show “Login” and “Logout” menu item based on the condition whether user is logged or logged out.

WordPress provides wp_nav_menu_items filter which can help us to achieve this.

“wp_nav_menu_items” filter provides two parameters

  1. $items:  Which provide the HTML list content for the menu items
  2. $args: An object containing wp_nav_menu() arguments

Add the following code into your theme functions.php file and it will add the relevant links

function wp_add_login_logout_link($items, $args) {
    // check for the right menu to add the menu item from
    // here we check for theme location of 'primary'
 if ($args->theme_location != 'primary')  return $items;
 
$loginoutlink = wp_loginout('index.php', false);
$items .= '<li>'. $loginoutlink .'</li>';
return $items;
}
add_filter('wp_nav_menu_items', 'wp_add_login_logout_link', 10, 2);

In the above code first we are making sure that we are only targeting our “primary” navigation and then adding the loggin/logged-out links based on user state.

If we have any questions or feedback about this then please contact me.

Comments 0
There are currently no comments.