I'm trying to build a submenu into my theme, and I've got it working except it shows even on top-level pages that don't have children.
How could I check that the current page (or current menu item) is either a parent or a child item (I'm pretty sure that logic holds up) in a given menu?
At the moment I'm trying to do this check outside of the menu function, because it has wrapper divs and a title that I won't want to show at all in cases where the page isn't a parent or a child. However, if the best answer to my problem is to output the whole thing via a custom walker I'm open to how that might work too.
Thanks in advance.
Edit: I've gotten a bit further but am now stuck, I can capture the submenu as a variable, but I can't do the check "If there's nothing in the submenu, show nothing". In the below code, $submenu
doesn't return false when there are no items even with that fallback_cb => false
.
$main_menu_id = 2; // Change to the main menu id for this install
$top_menu_id = 4; // Change to the top menu id for this install
$in_menu = '';
// Check what menu the page is in, if any
if( coepio_is_in_menu( $main_menu_id ) ) {
$in_menu = 'main-nav';
} else if( coepio_is_in_menu( $top_menu_id ) ) {
$in_menu = 'top-nav';
}
// If the page is in a menu...
if( $in_menu != '' ) {
// Capture submenu as a variable
$args = array(
'theme_location' => $in_menu,
'echo' => '0',
'sub_menu' => true,
'falback_cb' => false
);
$submenu = wp_nav_menu( $args );
// If the menu has items
if( $submenu ) {
echo 'Menu is good to go';
?>
<div id="submenu" class="sidebar cf" role="navigation">
<div class="widget">
<div id="submenu-title" class="widget-title">
<h4>In This Section</h4>
</div>
<div class="widget-content">
<?php
echo $submenu;
?>
</div>
</div>
</div><!-- #submenu -->
<?php
}
}
You may have noticed that 'sub_menu' => true
in the $args
. Here's the code that handles that, taken from another SO post.
// Submenus - required for the submenu (above) to work
// filter_hook function to react on sub_menu flag
function coepio_submenu( $sorted_menu_items, $args ) {
if ( isset( $args->sub_menu ) ) {
$root_id = 0;
// find the current menu item
foreach ( $sorted_menu_items as $menu_item ) {
if ( $menu_item->current ) {
// set the root id based on whether the current menu item has a parent or not
$root_id = ( $menu_item->menu_item_parent ) ? $menu_item->menu_item_parent : $menu_item->ID;
break;
}
}
$menu_item_parents = array();
foreach ( $sorted_menu_items as $key => $item ) {
// init menu_item_parents
if ( $item->ID == $root_id ) $menu_item_parents[] = $item->ID;
if ( in_array( $item->menu_item_parent, $menu_item_parents ) ) {
// part of sub-tree: keep!
$menu_item_parents[] = $item->ID;
} else {
// not part of sub-tree: away with it!
unset( $sorted_menu_items[$key] );
}
}
return $sorted_menu_items;
} else {
return $sorted_menu_items;
}
}
add_filter( 'wp_nav_menu_objects', 'coepio_submenu', 10, 2 );