How would you limit top level menu items in Sage 8.5

I have been searching for a way to limit the top level menu Items in Sage for a few days now and can’t seen to find a way that works.
I found this snippet of code on stackexchange

function my_nav_menu_objects( $sorted_menu_items, $args ) {
    if ( $args->theme_location != 'primary' )
        return $sorted_menu_items;
    $unset_top_level_menu_item_ids = array();
    $array_unset_value = 1;
    $count = 1;

    foreach ( $sorted_menu_items as $sorted_menu_item ) {

        // unset top level menu items if over count 4
        if ( 0 == $sorted_menu_item->menu_item_parent ) {
            if ( $count > 4 ) {
                unset( $sorted_menu_items[$array_unset_value] );
                $unset_top_level_menu_item_ids[] = $sorted_menu_item->ID;

        // unset child menu items of unset top level menu items
        if ( in_array( $sorted_menu_item->menu_item_parent, $unset_top_level_menu_item_ids ) )
            unset( $sorted_menu_items[$array_unset_value] );


    return $sorted_menu_items;
add_filter( 'wp_nav_menu_objects', 'my_nav_menu_objects', 10, 2 );

but when I try to use it in Sage it shows this

Warning:  call_user_func_array() expects parameter 1 to be a valid callback, function 'my_nav_menu_objects' not found or invalid function name in /sites/ on line 298

I can use the code in every theme that comes default with WordPress and the ones I downloaded from the WordPress theme repo. I just can’t figure out the problem it has with Sage.

If anyone could help
Thanks in advance

The code you’re trying to use isn’t working because you aren’t passing the namespace properly (lots of threads about this).

Do you need to do all of that? It seems like overkill. You should just need to add depth to wp_nav_menu:


It’s a big over kill but depth only eliminates the sub menu Items.
I need the top level items to not show up after 4 have been assigned, and that is the only code that I know of that will take make that happen.

Assuming you’re trying the code you provided on a namespaced file (is there a namespace at the top?), replace:

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


add_filter( 'wp_nav_menu_objects', __NAMESPACE__ . '\\my_nav_menu_objects', 10, 2 );

as per

That link was very helpful in explaining a whole mess of things I have been trying to use and thank you for point out the add_filter solution to my question much appreciated