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
- $items: Which provide the HTML list content for the menu items
- $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.