Skip to content

Instantly share code, notes, and snippets.

@scottlee
Created June 4, 2013 18:56
Show Gist options
  • Save scottlee/5708486 to your computer and use it in GitHub Desktop.
Save scottlee/5708486 to your computer and use it in GitHub Desktop.
If the current page has child menu items, display them. Hazzah!
<?php
/**
* Returns the submenu items of the parent menu item.
* @param $sorted_menu_items
* @param $args
* @return mixed
*/
function theme_wp_nav_menu_sub_menu_objects( $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', 'theme_wp_nav_menu_sub_menu_objects', 10, 2 );
function theme_primary_menu() {
$primary = wp_nav_menu( array(
'theme_location' => 'primary',
'container' => '',
'container_class' => '',
'echo' => false,
'fallback_cb' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
));
echo $primary;
}
function theme_subnav_menu() {
$subnav = wp_nav_menu( array(
'theme_location' => 'primary',
'container' => '',
'container_class' => '',
'fallback_cb' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s sub-menu">%3$s</ul>',
'echo' => false,
'sub_menu' => true
) );
$menu_items = substr_count( $subnav, 'class="menu-item ' );
if ( $menu_items != 0 ) {
echo $subnav;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment