Skip to content

Instantly share code, notes, and snippets.

@kopepasah
Created February 2, 2013 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kopepasah/4695132 to your computer and use it in GitHub Desktop.
Save kopepasah/4695132 to your computer and use it in GitHub Desktop.
This is an extension of the dynamic select menu function I wrote a while back. It will include children items of the top level parents.
<?php
function wp_nav_menu_select_sort( $a, $b ) {
return $a = $b;
}
function wp_nav_menu_select( $args = array() ) {
$defaults = array(
'theme_location' => '',
'menu_class' => 'select-menu',
);
$args = wp_parse_args( $args, $defaults );
if ( ( $menu_locations = get_nav_menu_locations() ) && isset( $menu_locations[ $args['theme_location'] ] ) ) {
$menu = wp_get_nav_menu_object( $menu_locations[ $args['theme_location'] ] );
$menu_items = wp_get_nav_menu_items( $menu->term_id );
$children = array();
$parents = array();
foreach ( $menu_items as $id => $data ) {
if ( empty( $data->menu_item_parent ) ) {
$top_level[$data->ID] = $data;
} else {
$children[$data->menu_item_parent][$data->ID] = $data;
}
}
foreach ( $top_level as $id => $data ) {
foreach ( $children as $parent => $items ) {
if ( $id == $parent ) {
$menu_item[$id] = array(
'parent' => true,
'item' => $data,
'children' => $items,
);
$parents[] = $parent;
}
}
}
foreach ( $top_level as $id => $data ) {
if ( ! in_array( $id, $parents ) ) {
$menu_item[$id] = array(
'parent' => false,
'item' => $data,
);
}
}
uksort( $menu_item, 'wp_nav_menu_select_sort' );
?>
<select id="menu-<?php echo $args['theme_location'] ?>" class="<?php echo $args['menu_class'] ?>">
<option value=""><?php _e( 'Navigation' ); ?></option>
<?php foreach ( $menu_item as $id => $data ) : ?>
<?php if ( $data['parent'] == true ) : ?>
<optgroup label="<?php echo $data['item']->title ?>">
<option value="<?php echo $data['item']->url ?>"><?php echo $data['item']->title ?></option>
<?php foreach ( $data['children'] as $id => $child ) : ?>
<option value="<?php echo $child->url ?>"><?php echo $child->title ?></option>
<?php endforeach; ?>
</optgroup>
<?php else : ?>
<option value="<?php echo $data['item']->url ?>"><?php echo $data['item']->title ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
<?php
} else {
?>
<select class="menu-not-found">
<option value=""><?php _e( 'Menu Not Found' ); ?></option>
</select>
<?php
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment