WordPress provides a highly flexible menu system. It’s very easy to create menu items and assign it to a menu and lastly assign the menu to a theme location. You can have different types of menu items like a page, category, external link. But one thing I always have been missing is the ability to add a login/log out link to the menu depending upon user’s login status. After going through WordPress hooks, I came across the hook to achieve this. The hook is wp_nav_menu_items, we can add a filter to this hook and can attach any menu item to a given menu. Let’s have one example here.
<?php add_filter( 'wp_nav_menu_items', 'wti_loginout_menu_link', 10, 2 ); function wti_loginout_menu_link( $items, $args ) { if ($args->theme_location == 'primary') { if (is_user_logged_in()) { $items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>'; } else { $items .= '<li><a href="'. wp_login_url(get_permalink()) .'">Log In</a></li>'; } } return $items; } ?>
The above function is for adding a log in/log out link to the primary theme location for menu. This is what we have implemented in the above example.
– First added a filter for wp_nav_menu_items hook and attached a function to it.
– After checking for ‘primary’ theme location, we have checked whether user is logged in or not.
– If logged in, we have showed the Log Out link otherwise the Log In link.
– We have passed the permalink of the currently viewing page to the login url so that user will be redirected to the current page after successful login.
That’s it. Happy Coding 🙂