Skip to content

Instantly share code, notes, and snippets.

@brandonbarringer
Last active January 19, 2021 17:12
Show Gist options
  • Save brandonbarringer/1f41b361e042697d40fdc506cd7fa379 to your computer and use it in GitHub Desktop.
Save brandonbarringer/1f41b361e042697d40fdc506cd7fa379 to your computer and use it in GitHub Desktop.
Sane Custom WP Menu
<?php
public function get_menu($menu_name) {
$locations = get_nav_menu_locations();
$menu_object = wp_get_nav_menu_object( $locations[ $menu_name ] );
$array_menu = wp_get_nav_menu_items($menu_object->term_id);
$menu = array();
foreach ($array_menu as $m) {
if (empty($m->menu_item_parent)) {
$menu[$m->ID] = array();
$menu[$m->ID]['ID'] = $m->ID;
$menu[$m->ID]['title'] = $m->title;
$menu[$m->ID]['url'] = $m->url;
$menu[$m->ID]['children'] = array();
}
}
$submenu = array();
foreach ($array_menu as $m) {
if ($m->menu_item_parent) {
$submenu[$m->ID] = array();
$submenu[$m->ID]['ID'] = $m->ID;
$submenu[$m->ID]['title'] = $m->title;
$submenu[$m->ID]['url'] = $m->url;
$menu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID];
}
}
return $menu;
}
<?php $menu_items = get_menu('main-menu'); ?>
<nav>
<ul>
<?php foreach ($menu_items as $item) : ?>
<li>
<a href="<?= $item['url'] ?>" title="<?= $item['title'] ?>"><?= $item['title'] ?></a>
<?php if( !empty($item['children']) ):?>
<ul class="sub-menu">
<?php foreach($item['children'] as $child): ?>
<li>
<a href="<?= $child['url'] ?>" title="<?= $child['title'] ?>"><?= $child['title'] ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
<ul>
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment