7

I want to hide the div class "navmain2" if the menu is empty. See code below:

<!-- Start main navigation --> <div class="navmain2"> <div id="logo"></div> <!-- Gets main menu by id --> <span></span> <?php wp_nav_menu( array( 'menu' => 11, 'container' =>false, 'menu_class' => 'nav', 'echo' => true, 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'depth' => 0, 'walker' => new description_walker()) ); ?> <!-- /main menu --> <div id="klicka">Click here! Click here! Click here</div> </div><!-- /main navigation -->--> 

I have a logo and a div with text inside navmain2 as you can see.

The question is:

Is it possible to hide the whole navmain2 div if the wp_nav_menu is empty?

4 Answers 4

13

Assign the menu to a string:

$menu = wp_nav_menu( array ( 'echo' => FALSE, 'fallback_cb' => '__return_false' ) ); if ( ! empty ( $menu ) ) { echo '<div class="navmain2">' . $menu . '</div>'; } 
3
  • So should i edit the code or this is a seperate function that ill add in the same page ? Commented Jan 23, 2013 at 23:47
  • @MeiasSafa Use it instead of your code at the same place. Commented Jan 24, 2013 at 3:17
  • Cant get it to work. Because i have 2 divs in the main page. one called navmain and the other navmain2 and i just wanna hide navmain2 if it is empty. Commented Jan 28, 2013 at 12:42
6

If you wanted to check there is a menu assigned you could use has_nav_menu(). Passing through the registered menu id as registered via register_nav_menu()

 <?php if ( has_nav_menu( 'primary' ) ) { ?> <div class="navmain2"> </div> <?php } 

Note: This function will output the div if the location primary has a menu assigned, it will also output the div if the menu is assigned and empty

2
  • 1
    This should be the accepted answer, it's much more clearer then the current. I would just use the other format for the if block: if () : ?> <?php endif; when mixing with HTML. Commented Apr 10, 2019 at 14:32
  • Confirmed working in WordPress v4.9 for people still running old builds. Commented Jan 15, 2020 at 23:43
1

Determines whether a registered nav menu location has a menu assigned to it. know more

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

Solution nr 2:

Is to hide the div thru Js.

$('#jqm-home').live("pagecreate", function () { $(".navmain2").each(function () { if ($(this).children("ul").length == 0) { $(this).hide(); } }); }); 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.