how to create WordPress menu shortcode

How To Create WordPress Menu Shortcode: Theme Development

Used before category names. Blog WordPress WordPress Development

From WordPress version 3 onwards, we can use the wp_nav_menu function to create and display WordPress navigation menus. In the following, we will explain how to add a shortcode to the page or post and display the menu inside it, and how to add a shortcode inside the menu like submenus. You can use this article to display your desired menu anywhere on the WordPress website using a shortcode, and you can also put any shortcode you want in your menu item to be displayed in the navigation menu.

For example, we created the menu using the Elementor page builder, and we want to display that menu in the navigation section of the site as a sub-menu (mega menu). In this case, we can easily add the shortcode of the designed menu to the desired menu in the list section so that it can be displayed in that section.

Create a shortcode to display the menu on the WordPress page

The wp_nav_menu function is used to display the menu in the template. In this section, we use the possibility of creating a shortcode in WordPress and this function to create our custom shortcode.

function hs_list_menu($atts, $content = null)
{
    extract(
        shortcode_atts(
            [
                'menu' => '',
                'container' => 'div',
                'container_class' => '',
                'container_id' => '',
                'menu_class' => 'menu',
                'menu_id' => '',
                'echo' => true,
                'fallback_cb' => 'wp_page_menu',
                'before' => '',
                'after' => '',
                'link_before' => '',
                'link_after' => '',
                'depth' => 0,
                'walker' => '',
                'theme_location' => '',
            ],
            $atts
        )
    );
    return wp_nav_menu([
        'menu' => $menu,
        'container' => $container,
        'container_class' => $container_class,
        'container_id' => $container_id,
        'menu_class' => $menu_class,
        'menu_id' => $menu_id,
        'echo' => false,
        'fallback_cb' => $fallback_cb,
        'before' => $before,
        'after' => $after,
        'link_before' => $link_before,
        'link_after' => $link_after,
        'depth' => $depth,
        'walker' => $walker,
        'theme_location' => $theme_location,
    ]);
}
add_shortcode('listmenu', 'hs_list_menu');

Now we can use this shortcode anywhere on the website to display the desired menu. For example, suppose you have a menu called “Main Menu” and you want to display this menu inside your post. You can display the “Main Menu” by adding the following shortcode.

Open your post and add the following shortcode to display “Main Menu” items inside your post.

[listmenu menu="Main Menu"]

If you look at the code above, you will notice that the menu parameter contains the name of the menu, which is sent to the shortcode and is placed in the menu section inside the shortcode, and the wp_nav_menu function displays the menu whose name is “Main Menu”.

Any parameters you pass to the shortcode will be placed inside the function. For example:

[listmenu menu="Main Menu" menu_class="main-menu-class"]

This example also adds the main-menu-class class to the menu.

Adding a shortcode to the navigation menu

You may have seen mega menus on many sites and wondered how these menus are created. If you have used the Woodmart template, you will notice that this template uses page builders such as Elementor to design mega menus.

In this section, you will learn how to implement this menu using a shortcode. This is actually adding the Elementor page builder Template to the menu through the WordPress shortcode.

For this, all the codes will be placed in the template file. You can put these codes in your own custom plugin.

First, open the functions.php file of your template and put the following codes in it.

add_filter('wp_nav_menu_items', 'do_shortcode');

This code tells WordPress that we will use shortcodes in WordPress menu items.

function hs_menu_content($atts, $content = null){
	extract(
        shortcode_atts(
            [
                'id' => '',
            ],
            $atts
        )
    );
	$args = array(
		'post_type'      => 'elementor_library',
		'tabs_group' => 'library',
		'p' => $id,
		'elementor_library_type' => 'page',
	);
	$elementor_templates = get_posts($args);
	foreach ($elementor_templates as $elementor_template) {
		return $elementor_template->post_content;
	}
}
add_shortcode('menu_content', 'hs_menu_content');

This code actually defines a short code that takes the Elementor page builder template ID and displays its designed content. Because the retrieval of the designed content is done through the identifier, so we will have only one template content that returns the content in the foreach loop.

To view the template ID, go to the “Templates” menu in the WordPress dashboard and open the desired template. Then you can see your template ID in the URL address bar.

function hs_menu_item_shortcode($item_id, $item)
{
    $menu_item_shortcode = get_post_meta($item_id, '_menu_item_shortcode', true); ?>
	<div>
	    <span class="shortcode">
			<?php _e('Item Shortcode', 'textdomain'); ?>
		</span><br />
	    <input type="hidden" class="nav-menu-id" value="<?php echo $item_id; ?>" />
	    <div class="input-holder">
	        <input type="text" name="menu_item_shortcode[<?php echo $item_id; ?>]" id="menu-item-shortcode-<?php echo $item_id; ?>" value="<?php echo esc_attr($menu_item_shortcode); ?>" />
	    </div>
	</div>
	<?php
}
add_action('wp_nav_menu_item_custom_fields', 'hs_menu_item_shortcode', 10, 2);

This code creates a section titled “Item Shortcode” in the menu section of the WordPress Dashboard for each item in the menu, where the shortcode defined above is placed in this box.

WordPress Menu Shortcode
function hs_save_menu_item_shortcode($menu_id, $menu_item_db_id)
{
    if (isset($_POST['menu_item_shortcode'][$menu_item_db_id])) {
        $sanitized_data = sanitize_text_field($_POST['menu_item_shortcode'][$menu_item_db_id]);
        update_post_meta($menu_item_db_id, '_menu_item_shortcode', $sanitized_data);
    } else {
        delete_post_meta($menu_item_db_id, '_menu_item_shortcode');
    }
}
add_action('wp_update_nav_menu_item', 'hs_save_menu_item_shortcode', 10, 2);

This code stores the value (shortcode) entered in the box in the WordPress database.

function hs_display_menu_item_shortcode($item_output, $item) {
	if (!is_object($item) || !isset($item->object)) {
		return $item_output;
	}
	if (is_object($item) && isset($item->ID)) {
		$menu_item_shortcode = get_post_meta($item->ID, '_menu_item_shortcode', true);
		if (!empty($menu_item_shortcode)) {
			$item_output .= '<div class="sub-menu">'.do_shortcode($menu_item_shortcode).'</div>';
		}
	}
	return $item_output;
}

add_filter('walker_nav_menu_start_el','hs_display_menu_item_shortcode',20,2);

In this code, the shortcode part of the menu is read, and using the shortcode we defined a little earlier, its content is displayed in the menu as a sub-menu.

As you learned, you can design your own sub-menu in the templates section of Elementor’s page builder and add it to the menu as a sub-menu using the WordPress shortcode.

Menu shortcodes plugins

1. Shortcode in Menus

Shortcode in Menus plugin allows you to add shortcodes in WordPress navigation menu links. It also allows you to add HTML codes to navigation menus.

2. menu shortcode

Using the menu shortcode plugin, you can call and display the menu you want anywhere on your website through a shortcode. This is actually the opposite of the above plugin.

[listmenu menu="menu name goes here" menu_id="menu id goes here"]

For example:

[listmenu menu="quick footer" menu_id="footer_menu"]