While working with WordPress there are times that it can be very useful to check if a menu is empty before outputting markup. One example is for displaying dynamic, custom, menus in a sidebar where you may not want to output any markup if the menu is empty. This is actually the default functionality of the wp_nav_menu method, but generally menus are wrapped in modules and if the menu is empty one may want to omit the entire module. Since wp_nav_menu will return false if echo is set to false and the menu is empty we can use this with a simple conditional statement to determine if the menu module markup should be output or not.
if (wp_nav_menu( array( 'theme_location' => 'secondary', 'echo' => false )) !== false) { // This is where your menu module would go wp_nav_menu( array( 'theme_location' => 'secondary' )); }
Its a rather simple solution that just requires a solid understanding of the underlying functionality built into the nav-menu-template.php WordPress core file.
Leave a Reply