wp_nav_menu: show menu only if one exists, otherwise show nothing

I’m trying to use wp_nav_menu to only display a menu if one exists, otherwise, display nothing.

If I delete the menu, it will output a list of the pages.

Read More

My functions.php file contains:

if (function_exists('register_nav_menus')) {
register_nav_menus (
array('main_nav' => 'Main Navigation Menu'));}

How can I use wp_nav_menu to only display a menu if one exists, otherwise show nothing?

Related posts

Leave a Reply

4 comments

  1. Use has_nav_menu(), and test for theme_location, rather than menu_id:

    <?php
    if ( has_nav_menu( $theme_location ) ) {
        // User has assigned menu to this location;
        // output it
        wp_nav_menu( array( 
            'theme_location' => $theme_location, 
            'menu_class' => 'nav', 
            'container' => '' 
        ) );
    }
    ?>
    

    You can output alternate content, by adding an else clause.

    EDIT

    You need to replace $theme_location with your actual theme_location:

    <?php
    if ( has_nav_menu( 'main_nav' ) ) {
        // User has assigned menu to this location;
        // output it
        wp_nav_menu( array( 
            'theme_location' => 'main_nav', 
            'menu_class' => 'nav', 
            'container' => '' 
        ) );
    }
    ?>
    
  2. You can just specify false as the fallback_cb argument of wp_nav_menu. Nothing will show up — rather, wp_nav_menu will return false (echoing nothing out).

    <?php
    wp_nav_menu(array( 
        'theme_location' => $main_nav, 
        'menu_class'     => 'nav', 
        'container'      => '',
        'fallback_cb'    => false
    ));
    
  3. You can just register menu firstly without specifying the location.
    In functions.php:

    add_action( 'init', 'register_my_menus' );
    function register_my_menus() {  
        register_nav_menus(
            array(
                'header' => __( 'Header Menu' )
            )
        );
    }
    

    And when you call the menu in header.php, check with has_nav_menu():

    if ( has_nav_menu( 'header' ) ) {
        wp_nav_menu( array( 'theme_location' => 'header' ) ); 
    }