Skip to content

Instantly share code, notes, and snippets.

@bmcalister
Last active March 6, 2023 13:07
Show Gist options
  • Save bmcalister/6b822b8625d0bb59080d to your computer and use it in GitHub Desktop.
Save bmcalister/6b822b8625d0bb59080d to your computer and use it in GitHub Desktop.
One dimensional wordpress nav object to nested array
<?php
class Nested_nav {
public $wp_nav;
public $nested_nav;
function __construct($menu, $args = null) {
$this->wp_nav = wp_get_nav_menu_items($menu, $args);
$this->nested_nav = $this->buildTree( $this->wp_nav );
}
private function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element->menu_item_parent == $parentId) {
$children = $this->buildTree($elements, $element->ID);
if ($children) {
$element->children = $children;
}
$branch[] = $element;
}
}
return $branch;
}
}
// $nav = new Nested_nav('main');
// print_r($nav->wp_nav);
// print_r($nav->nested_nav);
?>
@dougblackjr
Copy link

This is a lifesaver! Thank you!

@stzoran1
Copy link

stzoran1 commented Mar 6, 2023

Truly lifesaver ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment