Skip to content

Instantly share code, notes, and snippets.

@phpdave
Created March 3, 2015 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phpdave/2276323b022f1b7ff79d to your computer and use it in GitHub Desktop.
Save phpdave/2276323b022f1b7ff79d to your computer and use it in GitHub Desktop.
Get nav menu ID by "page id" and build sub navigation menu for that parent - WordPress PHP code
<?php
//this code is located in themes/{theme name}/page-templates/mypagetemplate.php in an area where i want to output the menu
//Get the Post/Page Id of the parent
if ($post->post_parent)
{
//go through post ancestors to find parent
$ancestors = get_post_ancestors($post->ID);
$parentPostId = $ancestors[count($ancestors) - 1];
}
else
{
//this page is the parent us the Post Id of this page
$parentPostId = $post->ID;
}
$parentNavMenuId=0;
//Set this to your menu
$menu_name = 'primary';
if (( $locations = get_nav_menu_locations() ) && isset($locations[$menu_name]))
{
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = '<ul id="menu-' . $menu_name . '">';
//Find parent menu id by the post id
foreach ((array) $menu_items as $key => $menu_item)
{
if ($menu_item->object_id == $parentPostId)
{
$parentNavMenuIds[] = $menu_item->ID;
}
}
foreach ((array) $menu_items as $key => $menu_item)
{
if (in_array($menu_item->menu_item_parent,$parentNavMenuIds))
{
$title = $menu_item->title;
$url = $menu_item->url;
$menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
}
}
$menu_list .= '</ul>';
}
else
{
$menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
}
echo $menu_list;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment