Skip to content

Instantly share code, notes, and snippets.

@franz-josef-kaiser
Forked from GhostToast/menu_loader_exploder.php
Last active December 19, 2015 05:08
Show Gist options
  • Save franz-josef-kaiser/5901582 to your computer and use it in GitHub Desktop.
Save franz-josef-kaiser/5901582 to your computer and use it in GitHub Desktop.
<?php
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations['topnav'] );
$menu_items = wp_get_nav_menu_items( $menu->term_id, array(
'order' => 'DESC',
) );
?>
<select class="the-selectors" onChange="document.location.href=this.options[this.selectedIndex].value;">
<option value="">
<?php _e( 'Please Select', 'your_textdomain' ); ?>
</option>
<?php
$i = 0;
$html = '';
foreach ( $menu_items as &$item )
{
if ( 0 === $item->menu_item_parent )
{
$item->sub_menu = 0;
}
// the last node was my parent. I am first born, I shall gain a level now.
elseif(
isset( $menu_items[ $i -1 ] )
AND $menu_items[ $i -1 ]->ID === $item->menu_item_parent
)
{
$item->sub_menu = $menu_items[ $i -1 ]->sub_menu +1;
}
// The last node is my sibling. We share a parent.
// I shall reference my sibling's sub_menu:
elseif(
isset( $menu_items[ $i -1 ] )
AND $menu_items[ $i -1 ]->menu_item_parent === $item->menu_item_parent
)
{
$item->sub_menu = $menu_items[ $i -1 ]->sub_menu;
}
// I have a parent, but it's not same as last node.
// I shall reference my last known sibling:
else
{
for( $a = $i -1; $a >= 0; $a-- )
{
if (
isset( $menu_items[ $a ] )
AND $menu_items[ $a ]->menu_item_parent === $item->menu_item_parent
)
{
$item->sub_menu = $menu_items[ $a ]->sub_menu;
break;
}
}
}
$html .= sprintf(
'<option value="%s">%s%s%s</option>',
$item->url,
str_repeat( '-&nbsp;', count( $item->submenu ) -1 ),
$item->title,
'#' === $item->url ? '&raquo;' : ''
);
$i++;
}
echo $html;
unset( $locations, $menu, $menu_items, $html, $i, $a );
?>
</select>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment