I'm using this function to add an item to my primary nav when on mobile, but its adding the item to all my navs instead of only the primary nav. How or where can I add a parameter to specify which nav is getting the add_last_nav_item()
if ( wp_is_mobile() ) {
function add_last_nav_item($items) {
return $items .= '<li ><a href="#myModal" role="button" data-toggle="modal">TEST</a></li>';
}
add_filter('wp_nav_menu_items','add_last_nav_item');
}
CodePudding user response:
You can check the args
that are passed to the wp_nav_menu_items
filter:
if ( wp_is_mobile() ) {
function add_last_nav_item($items, $args) {
// Check the menu
if ( $args->theme_location == 'your-menu-here' ) {
return $items .= '<li ><a href="#myModal" role="button" data-toggle="modal">TEST</a></li>';
}
// Returns the nav items if the condition isn't met.
return $items;
}
add_filter('wp_nav_menu_items','add_last_nav_item', 10, 2);
}
Here is the documentation on wp_nav_menu_items
and here's the link to the documentation for the $args
that are passed to the filter: wp_nav_menu
As an aside, wp_is_mobile()
isn't the best check if a user is on a mobile device. You might consider adding the menu item to the menu you want in the WP Admin area, and then just adding a class
that hides it on desktop.