wp_nav_menu always falls back to a menu

hey all,
i’m writing an automated function that generates a menu from a function. it calls wp_nav_menu on each item from an array, because i want this to be dynamic. the problem is, no matter how i set it, if the menu doesn’t exist, wp_nav_menu is generating a menu, eg the ‘default’. here is my code (items is just a set of strings):

for($i=0;$i<count($items);$i++) {

    $themenu=$items[$i];

    $mymenu = wp_nav_menu(array(
            'menu' => $themenu,
            'menu_class' => 'mymenu',
            'container' => 'false',
            'fallback_cb' => 'false',
            'echo' => false
            )
        );  

    echo $themenu;

    }

i know its partially working, because if $themenu exists, it shows the correct one. but if it doesn’t, it’ll just show any menu! not just annoying, but also actively breaks the user experience.

Related posts

Leave a Reply

3 comments

  1. wp_nav_menu() indeed tries a lot to provide you with a menu, and fallback_cb is only executed when nothing else works. From the code:

    • If menu is provided and refers to an existing menu (looked up via wp_get_nav_menu_object(), which accepts an id, slug or name), this will be the menu
    • Otherwise, if theme_location is set to a registered menu location, this will be passed to wp_get_nav_menu_object()
    • Otherwise, WordPress will search for the first existing menu that has items and use that
    • Otherwise, fallback_cb is called, which by default is wp_page_menu, which is a menu of all the pages

    So if you only want to use the menu argument, you should test this yourself by calling wp_get_nav_menu_object(). Only if this returns something you should call wp_nav_menu().

  2. Try wrapping your echo inside of a has_nav_menu() conditional:

    for($i=0;$i<size($items);$i++) {
    
        $themenu=$items[$i];
    
        $mymenu = wp_nav_menu(array(
                'menu' => $themenu,
                'menu_class' => 'mymenu',
                'container' => 'false',
                'fallback_cb' => 'false',
                'echo' => false
                )
            );  
    
        if ( has_nav_menu( $themenu ) ) echo $themenu;
    
        }
    

    (If I’m following your code correctly…)

  3. From the Codex entry for wp_nav_menu():

    $fallback_cb (string) (optional) If
    the menu doesn’t exist, the fallback
    function to use. Set to false for no
    fallback.
    Default: wp_page_menu

    So have you tried passing 'fallback_cb' => false?

    EDIT:

    As per the comment below, 'fallback_cb' => 'false' is telling wp_nav_menu() to fallback to a function called false(), and since this function doesn’t exist, it falls back to its normal fallback, wp_page_menu(). So, use 'fallback_cb' => false (i.e. a boolean value, rather than a string value).