Remove a menu item in menu

I know this has been asked many times. But from what i got after searching, i could not understand much. I have used wp_update_nav_menu_item to add menu items programatically. But i don’t know how to remove a specific menu item. In one of the forums, it has been told to unset the array element (forum). But i did not understand it. Can anybody explain how to do it?

3 s
3

I think the best way to remove a menu item from a menu is by hooking to wp_nav_menu_objects filter (@Otto answer from the thread you mentioned). And the way you use is first check for the correct menu to filter, and then search for the menu item and remove it by unsetting it from the $sorted_menu_objects array.

This following example will remove the Uncategorized menu item from the menu that is on the secondary-menu theme location:

add_filter('wp_nav_menu_objects', 'ad_filter_menu', 10, 2);

function ad_filter_menu($sorted_menu_objects, $args) {

    // check for the right menu to remove the menu item from
    // here we check for theme location of 'secondary-menu'
    // alternatively you can check for menu name ($args->menu == 'menu_name')
    if ($args->theme_location != 'secondary-menu')  
        return $sorted_menu_objects;

    // remove the menu item that has a title of 'Uncategorized'
    foreach ($sorted_menu_objects as $key => $menu_object) {

        // can also check for $menu_object->url for example
        // see all properties to test against:
        // print_r($menu_object); die();
        if ($menu_object->title == 'Uncategorized') {
            unset($sorted_menu_objects[$key]);
            break;
        }
    }

    return $sorted_menu_objects;
}

Leave a Comment