How do you return a menu with the menu name?

in functions.php, I’ve defined the following:

register_nav_menu( 'home_blocks', __( 'Home Page Posts', 'my_Theme' ) );

In /wp-admin/nav-menus.php, I’ve added a menu called Home Page Posts and assigned 3 posts to it and set it to be the item associated with Home Page Posts as the menu location.

Read More

In index.php, I’ve added the following:

if ( has_nav_menu( 'primary' ) ) {
    echo 'has primary<br />';
} else {
    echo 'no primary<br />';
}
if ( has_nav_menu( 'home_blocks' ) ) {
    echo 'has home blocks<br />';
} else {
    echo 'no home_blocks<br />';
}

Both of the successful conditions are echoed.

When I try to return the menu contents so I can run some inline custom output based on post_id, I attempted the following code and got NULL or string(0) “”, depending on what values I put for the location and menu name. What way are these values associated and how would I get the menu back?

$defaults = array(
    'theme_location'  => 'home_blocks',
    'menu'            => '',
    'container'       => '',
    'container_class' => '',
    'container_id'    => '',
    'menu_class'      => '',
    'menu_id'         => '',
    'echo'            => 1,
    'fallback_cb'     => '',
    'before'          => '',
    'after'           => '',
    'link_before'     => '',
    'link_after'      => '',
    'items_wrap'      => '',
    'depth'           => 0,
    'walker'          => ''
);

$menu = wp_nav_menu( $defaults );

var_dump( $menu );

Related posts

2 comments

  1. If you want to return the output of wp_nav_menu(), instead of echo-ing it, you should replace

    'echo'            => 1,
    

    with

    'echo'            => 0,
    

    Then you should get something out of var_dump( $menu );.

    You can read more about the input parameters in the Codex.

    Update:

    You should remove this line:

    'items_wrap'      => '',
    

    to use the default which is:

    'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
    

    You can also target a specific menu with the 'menu' parameter, if you haven’t selected a location for it, in the menu settings page. Currently you have it set to '';

  2. $menu = wp_nav_menu( array('theme_location' => 'home_blocks', 'echo' => 0) );
    var_dump($menu); //works just fine
    

    You are essentially overriding all the defaults that wp_nav_menu has when you make an array and assign its values to an empty string.

    Delete that default array and only set the items you need like in the example I have in the array above.

Comments are closed.