Skip to content

Instantly share code, notes, and snippets.

@kevinruscoe
Last active August 29, 2015 14:11
Show Gist options
  • Save kevinruscoe/3d0266a4884a94dd0a28 to your computer and use it in GitHub Desktop.
Save kevinruscoe/3d0266a4884a94dd0a28 to your computer and use it in GitHub Desktop.
Returns a child UL of a WordPress formatted menu
function get_nav_menu_part( $menu_name, $sub_item_to_find ){
if( !is_string($menu_name) ){
return;
}
if( !is_string($sub_item_to_find) && !is_integer($sub_item_to_find) ){
return;
}
// Get the page ID we're looking for to return the ID, either by string or ID
if( is_string( $sub_item_to_find )){
$page_to_find = get_page_by_title( $sub_item_to_find );
$page_id = $page_to_find->ID;
$dom_class_name = "page-item-$page_id";
}
if( is_integer($sub_item_to_find) ){
$dom_class_name = "page-item-$sub_item_to_find";
}
// Get main menu as HTML
$menu_html = wp_nav_menu(
array(
'menu' => $menu_name,
'echo' => false
)
);
// Create a DOM element, and push our menu HTML into it
$dom = new DOMDocument();
$dom->loadHTML($menu_html);
// find: li[class='$dom_class_name'] ul
$finder = new DomXPath($dom);
$found_marching_nodes = $finder->query("//li[contains(@class, '$dom_class_name')]/ul");
// No nodes? Return the list main menu
if( !$found_marching_nodes ){
return $menu_html;
}
// Push the found nodes into a new DOM, then return the HTML
$child_dom = new DOMDocument();
foreach( $found_marching_nodes as $node ){
$child_dom->appendChild($child_dom->importNode($node,true));
}
$output = $child_dom->saveHTML();
return $output;
}
// Usage:
get_nav_menu_part('Main Navigation', 'Our Services')
// FFS - Or use: http://wordpress.stackexchange.com/questions/2802/display-a-portion-branch-of-the-menu-tree-using-wp-nav-menu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment