Skip to content

Instantly share code, notes, and snippets.

@Chukatuk
Forked from vwasteels/getMenuHierarchically.md
Last active April 20, 2017 13:07
Show Gist options
  • Save Chukatuk/321e02d07a01612909d01affe347a874 to your computer and use it in GitHub Desktop.
Save Chukatuk/321e02d07a01612909d01affe347a874 to your computer and use it in GitHub Desktop.
Retrieve menu items hierarchically in Wordpress
```php
/**
* Get Menu Items From Location
*
* @param $location : location slug given as key in register_nav_menus
*/
function getMenuItemsFromLocation($location) {
$theme_locations = get_nav_menu_locations();
$menu_obj = get_term( $theme_locations[$location], 'nav_menu' );
return is_wp_error($menu_obj) ? [] : getMenuItemsForParent($menu_obj->slug, 0)
}
/**
* Get Menu Items For Parent
*
* @param $menuSlug : menu slug for the CMS entry (not the key in register_nav_menus)
* @param $parentId
* @return array of items formatted as objects with : name / url / children (fetched recursively)
* object and object_id are used to get custom fields
*/
function getMenuItemsForParent($menuSlug, $parentId) {
$tmpItems = wp_get_nav_menu_items($menuSlug);
$items = [];
foreach ( $tmpItems as $tmpItem ) {
$item = new stdClass;
if ($tmpItem->menu_item_parent == $parentId) {
$item->title = $tmpItem->title;
$item->url = $tmpItem->url;
$item->object = $tmpItem->object;
$item->object_id = $tmpItem->object_id;
$item->children = getMenuItemsForParent($menuSlug, $tmpItem->ID);
$items[] = $item;
}
}
return $items;
}
/**
* Usage
*/
$menuItems = getMenuItemsFromLocation('footer_menu');
// will return :
[
'name' => 'Menu item 1'
'url' => '/my-post-type/my-url-1'
'children' => [
'name' => 'Menu item 2'
'url' => '/external-custom-link'
'children' => []
],
// etc...
]
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment