Skip to content

Instantly share code, notes, and snippets.

@rafa-acioly
Created November 18, 2017 15:48
Show Gist options
  • Save rafa-acioly/e2ea855d6d2251287779aa2fd5273f0a to your computer and use it in GitHub Desktop.
Save rafa-acioly/e2ea855d6d2251287779aa2fd5273f0a to your computer and use it in GitHub Desktop.
Organize all menus with their respectives submenus.
<?php
function generateMenu ()
{
$array_menu = wp_get_nav_menu_items('main-menu');
$menu = [];
$submenu = [];
foreach ($array_menu as $item_menu) {
if (empty($item_menu->menu_item_parent)) {
$menu[$item_menu->ID] = [
'ID' => $item_menu->ID,
'title' => $item_menu->title,
'url' => $item_menu->url,
'children' => [],
];
} else {
$submenu[$item_menu->ID] = [
'ID' => $item_menu->ID,
'title' => $item_menu->title,
'url' => $item_menu->url
];
$menu[$item_menu->menu_item_parent]['children'][$item_menu->ID] = $submenu[$item_menu->ID];
}
}
return $menu;
}
add_action('createMainMenu', 'generateMenu');
/*
Output example:
Array
(
[80] => Array
(
[ID] => 80
[title] => Quem somos
[url] => http://wordpress.dev/quem-somos/
[children] => Array
(
[56] => Array
(
[ID] => 56
[title] => História
[url] => http://wordpress.dev/historia/
)
[97] => Array
(
[ID] => 97
[title] => Missão
[url] => http://wordpress.dev/missao/
)
)
)
[79] => Array
(
[ID] => 79
[title] => Exames
[url] => http://wordpress.dev/exames/
[children] => Array
(
)
)
[78] => Array
(
[ID] => 78
[title] => Cirurgias
[url] => http://wordpress.dev/cirurgias/
[children] => Array
(
)
)
[77] => Array
(
[ID] => 77
[title] => Corpo clinico
[url] => http://wordpress.dev/corpo-clinico/
[children] => Array
(
)
)
[76] => Array
(
[ID] => 76
[title] => Convênios
[url] => http://wordpress.dev/convenios/
[children] => Array
(
)
)
[75] => Array
(
[ID] => 75
[title] => Área médica
[url] => http://wordpress.dev/area-medica/
[children] => Array
(
)
)
[74] => Array
(
[ID] => 74
[title] => Pré-agendamento
[url] => http://wordpress.dev/pre-agendamento/
[children] => Array
(
)
)
[58] => Array
(
[ID] => 58
[title] => Contato
[url] => http://wordpress.dev/contato/
[children]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment