Blog

Add a Submenu Shortcode to WordPress

There are many plugins and code snippets for adding an entire navigation menu to a page in WordPress, but what if you want to add only a single submenu? Here we have for you a code snippet that provides a shortcode to do just that. You can add this to your theme’s functions.php file.

add_filter( 'wp_nav_menu_objects', 'submenu_limit', 10, 2 );

function submenu_limit( $items, $args ) {

if ( empty($args->submenu) ) {
return $items;
}

$parent_id = array_pop( wp_filter_object_list( $items, array( 'title' => $args->submenu ), 'and', 'ID' ) );
$children = submenu_get_children_ids( $parent_id, $items );

foreach ( $items as $key => $item ) {

if ( ! in_array( $item->ID, $children ) ) {
unset($items[$key]);
}
}

return $items;
}

function submenu_get_children_ids( $id, $items ) {

$ids = wp_filter_object_list( $items, array( 'menu_item_parent' => $id ), 'and', 'ID' );

foreach ( $ids as $id ) {
$ids = array_merge( $ids, submenu_get_children_ids( $id, $items ) );
}

return $ids;
}

add_shortcode('navigation_menu','navigation_menu');
function navigation_menu($atts,$content){

$atts = shortcode_atts( array(
'menu_class' => 'menu',
'menu' => '',
'submenu' => '',
'before' => '',
'after' => '',
'container' => 'div',
'container_class' => '',
'depth' => '',
'echo' => false
), $atts );

$content = wp_nav_menu(
array(
'menu' => sanitize_text_field($atts['menu']),
'submenu' => sanitize_text_field($atts['submenu']),
'before' => $atts['before'],
'after' => $atts['after'],
'menu_class' => sanitize_text_field($atts['menu_class']),
'container' => sanitize_text_field($atts['container']),
'container_class' => sanitize_text_field($atts['container_class']),
'depth' => sanitize_text_field($atts['depth']),
'echo' => false
)
);

return $content;
}

Usage:

[navigation_menu menu="Menu" submenu="Projects"]

“menu” would be the name of the navigation menu, and “submenu” would be the title of the submenu. Note that the submenu variable is case-sensitive, so if the title of a submenu is “PROJECTS” for example, you would need to put it that way in the shortcode. Here are some other options you can use:

before or after: Code to place before or after each submenu item
menu_class: CSS class to use for the submenu list
container: Type of container for the submenu, for example, defaults to div
container_class: CSS class to use for the submenu container
depth: Number of levels deep you wish to go into the submenu

We hope this code snippet is useful!

Share this Article