Menu.php 2.67 KB
<?php
namespace Tz\WordPress\Tools\Menu;
use Exception, Countable, Iterator;

function get_nav_menu($location) {
    $locations     = get_nav_menu_locations();
    if (!isset($locations[$location])) {
        throw new Exception("{$location} is not a defined menu location");
    }
    $menu_location = _get_nav_menu_object($locations[$location])->slug;
    $menu = _get_nav_menu_items($menu_location);
    _wp_menu_item_classes_by_context($menu);

    return $menu;
}


class HierarchicalMenu implements Countable, Iterator {
    private $contents = Array();
    private $current  = 0;

    private $id_lookup     = Array();
    private $target_lookup = Array();

    public function __construct(Array $menu, $parent = 0) {
        $last_id = $i = -1;
        $nest    = Array();

        foreach ($menu as $key => $realitem) {
            $item = clone $realitem;
            $item->_children = false;

            if ($item->menu_item_parent == $parent) {
                $i++;

                $this->contents[$i] = $item;
                $this->id_lookup[$item->ID] = $i;
                $this->target_lookup[$item->object_id] = $i;

                $last_id = $item->ID;
            } elseif ($item->menu_item_parent == $last_id) {
                $this->contents[$this->id_lookup[$last_id]]->_children = true;
                $this->contents[$this->id_lookup[$last_id]]->classes[] = 'menu-item-children';
                $nest[] = $last_id;

                $last_id = $item->ID;
            } elseif (count($nest) > 0) {
                $last_id = array_pop($nest);
                if (isset($this->id_lookup[$last_id])) {
                    $this->contents[$this->id_lookup[$last_id]]->_children = true;
                }
            }
        }

        $me = __CLASS__;
        foreach ($this->contents as $key => &$item) {
            if (true === $item->_children) {
                $item->{str_replace(Array(__NAMESPACE__, '\\'), '', $me)} = new $me($menu, $item->ID);
            }
            unset($this->contents[$key]->_children);
        }
    }

    public function count() {
        return count($this->contents);
    }

    public function current() {
        return $this->contents[$this->current];
    }

    public function key() {
        return $this->current;
    }

    public function next() {
        $this->current++;
    }

    public function rewind() {
        $this->rewind = 0;
    }

    public function valid() {
        return (isset($this->contents[$this->current]) ? true : false);
    }

    public function getItemByID($id) {
        return $this->id_lookup[$id] ?: false;
    }

    public function getItemByTarget($id) {
        return $this->target_lookup[$id] ?: false;
    }
}
?>