Why do I get null for $locations[$menu_name]?

347 Views Asked by At

I have saved my menu name as 'main_nav', and I tried to get all the items in it:

$menu_name = 'main_nav';
$locations = get_nav_menu_locations();

var_dump($locations[$menu_name]); // NULL

if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
    $menu = wp_get_nav_menu_object($locations[$menu_name]);
    $menu_items = wp_get_nav_menu_items($menu->term_id);

    $menu_list = '<nav>' ."\n";
    $menu_list .= "\t\t\t\t". '<ul>' ."\n";
    foreach ((array) $menu_items as $key => $menu_item) {
        $title = $menu_item->title;
        $url = $menu_item->url;
        $menu_list .= "\t\t\t\t\t". '<li><a href="'. $url .'">'. $title .'</a></li>' ."\n";
    }
}

But I get null for $locations[$menu_name]. Any ideas what have i missed?

1

There are 1 best solutions below

0
On

As the $menu_name try to apply the keys that were used in register_nav_menus function in your functions.php file.