Skip to content

Instantly share code, notes, and snippets.

@GhostToast
Last active December 19, 2015 03:09
Show Gist options
  • Save GhostToast/5888469 to your computer and use it in GitHub Desktop.
Save GhostToast/5888469 to your computer and use it in GitHub Desktop.
Creates a dropdown menu from a WordPress Nav Menu. Useful for sitting alongside regular menu for use in responsive designs, or where there's no room for a regular menu. Gracefully nests.
<?php
$menu_name = 'topnav'; // or whatever menu you want
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$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="">Please Select</option>
<?php
$i = 0;
foreach($menu_items as &$item){
if($item->menu_item_parent == 0){
$item->sub_menu = 0;
}
elseif(
isset($menu_items[$i - 1])
&& $item->menu_item_parent == $menu_items[$i - 1]->ID)
{
// The last node was my parent.
// I am first born, I shall gain a level now.
$item->sub_menu = $menu_items[$i - 1]->sub_menu + 1;
} elseif(
isset($menu_items[$i - 1])
&& $item->menu_item_parent == $menu_items[$i - 1]->menu_item_parent)
{
// The last node is my sibling. We share a parent.
// I shall reference my sibling's sub_menu
$item->sub_menu = $menu_items[$i - 1]->sub_menu;
} else {
// I have a parent, but it's not same as last node.
// I shall reference my last known sibling
for($a=$i-1; $a>=0; $a--){
if(
isset($menu_items[$a])
&& $item->menu_item_parent == $menu_items[$a]->menu_item_parent)
{
$item->sub_menu = $menu_items[$a]->sub_menu;
break;
}
}
}
echo '<option value="'.$item->url.'">';
for($z=0; $z<$item->sub_menu; $z++){
echo '-&nbsp;'; // or whatever characters you want to denote nesting
}
echo $item->title;
if($item->url == '#'){
echo '&raquo;'; // indicates non-link parent
}
echo '</option>';
$i++;
}
?>
</select>
@userabuser
Copy link

Good job, I have a similar snippet I've written that I use on a regular basis for just this very purpose. It's very useful, given that more and more sites need a responsive alternative or like you said, where a normal menu may not fit a given layout. Thanks for your contribution.

@GhostToast
Copy link
Author

Thanks. I thought about this over the weekend and realized I had nothing in place to indicate a non-link parent (where href="#"), so made a provision for that. I also realized I was making some goofy unnecessary calls to get page_id and whatnot, not realizing the menu_item had all the info I needed, so tidied that up a bit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment