Support » Themes and Templates » Ho to Hide a div if no items available
Ho to Hide a div if no items available
-
Hi, I use the following method to list sub-menu items in a page template.
Need help to show the div only if sub-menu items are available. if not it shows a blank stripe…<div class="bottom-menu"> <?php wp_nav_menu( array( 'theme_location' => 'main-menu', 'depth' => '1', 'submenu' => 'Investor Relations', ) ); ?> </div>
-
Try calling has_nav_menu() to check if a menu is assigned:
<?php if ( has_nav_menu( 'main-menu' ) : ?> <div class="bottom-menu"> ... code snipped for clarity ... </div><!-- .bottom-menu --> <?php endif; ?>
Hi stephen, since it gave a syntax error I used your method as following. but it didn’t work though…
<?php if ( has_nav_menu( 'main-menu' ) ) { ?> <div class="bottom-menu"> <?php wp_nav_menu( array( 'theme_location' => 'main-menu', 'depth' => '1', 'submenu' => 'Investor Relations', ) ); ?> </div> <?php } ?>
I’m sorry, I think I misunderstood something. You wouldn’t see any submenu items since you’re passing
'depth' => '1'
towp_nav_menu()
. Can you clarify what you’re trying to do?Yes, what I’m trying is; as a part of this page template, I will be displaying a list of sub-links related to a main page. Fetching them from Appearance > Menus.
This works fine.
Ex: If the menu structure is as follows;Careers
– Vacancies
– Apply Online
– FAQsIt lists only sub-menu items.
What I want is to hide the div if there is no sub-menu items.
Hope It’s clear and thanks for your replies. 🙂You might be able to do this without calling
wp_nav_menu()
by running a new query in your page template and checking for pages that have the current page as a parent. This requires that you’ve set the parent-child relationship, though (by selecting the appropriate page from the “Parent” dropdown in the “Page Attributes” panel in the editing screen).<?php $args = array( 'post_type' => 'page', 'post_parent' => get_the_id() ); $new_query = new WP_Query( $args ); if ( $new_query->have_posts() ) : while ( $new_query->have_posts() ) : $new_query->the_post(); the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); endwhile; endif; wp_reset_query(); ?>
Yes your method is correct. But in this situation, all sub-menu items are not child pages. Some are taxonomies, some are external links etc.
Also, displaying has no issues, all I want to know is a method to hide an empty looking div.
Your best bet would be to wrap the entire
<div>..</div>
in a conditional that checks whether there are any items to display. How are you checking for the appropriate items? I don’t see any argument named “submenu” inwp_nav_menu()
.
- The topic ‘Ho to Hide a div if no items available’ is closed to new replies.