Remove a menu item in menu

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

tech