Expanding the WordPress Nav Menu

WordPress has a good UI for managing the menus and display them in your theme using the wp_nav_menu() function. The thing here is that you’re limited to add only pages, categories or custom links. If you want to add some custom item, for example, let’s say “Login” or “Logout” link whether the current user is logged in, you wouldn’t be able to do that from the GUI. But, there is a filter that can help us to achieve this – wp_nav_menu_items().

The code is pretty simple. First I’m doing a conditional check to see if the user is logged in and based on that I’m displaying the “Login” or “Logout” element. The thing with this code is that it will apply for every menu we have registered on our site.

If we want to target a specific menu then we need to include the $args argument and say that we want this to execute only on specific theme location. Here is an example: