Menu.php
2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?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;
}
}
?>