Adding a Sub Menu Select Option To WordPress Pages

Often times it’s necessary to have very granular control on sub navigation for pages. This little snippet solves that issue. It adds a metabox to WordPress pages that allows users to select from an automatically generated list of menus that have been created through the default WP Menus functionality.

Add this to your functions.php file

$prefix = ‘_dbt_’;

$meta_boxes = array();

// Custom sub menu select

function makeMyMenus() {
$menus = get_terms( ‘nav_menu’, array( ‘hide_empty’ => false ) );
global $menuArray;
$menuArray = array(‘select a sub menu’);

foreach ( $menus as $menu ) {
$menuArray[] = $menu->name;
}
}
makeMyMenus();

// Adding sub menu drop down to pages.

$meta_boxes[] = array(
‘id’ => ‘sub_menu’,
‘title’ => ‘Sub Menu’,
‘pages’ => array(‘page’), // applicable post types
‘context’ => ‘side’,
‘priority’ => ‘low’,
‘fields’ => array(
array(
‘name’ => ‘Sub Menu’,
‘desc’ => ‘The sub menu for this page created via Appearance > Menus’,
‘id’ => $prefix . ‘custom_menu’,
‘type’ => ‘select’,
‘options’ => $menuArray
)
)
);

Front end use. Place this in your theme files where you want the menu to appear

ID, ‘_dbt_custom_menu’, true) == true ) {
$menuName = get_post_meta($post->ID, ‘_dbt_custom_menu’, true);
wp_nav_menu( array(‘menu’ => $menuName, ‘fallback_cb’ => false ));
} // end if has link ?>