WordPress provides a highly flexible menu system. Its 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 page, category, external link. But one thing I always have been missing is the ability to add a log in/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. Lets have one example here.
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.