How to Create Menu Shortcode Without Plugin in WordPress

Bhuvi: Hey… I am looking for something to display menus that I choose on the WordPress page or post on the fly…is it possible?.

DIWP: Yup Man…of Course. You can do that by just creating a simple shortcode for the menu and then just add that shortcode in the page or post where you want to display the menu.

Advertisement

Bhuvi: Sounds Interesting but how to do that?

DIWP: Don’t worry, Here is the code snippets that will create a shortcode for the menu in WordPress. Just add this code in your theme’s function.php file.

//==============================================================
//Shortcode to Display Menus
//==============================================================

function diwp_menu_shortcode($attr){

	$args = shortcode_atts(array(

				'name'  => '',
				'class' => ''

				), $attr);

	return wp_nav_menu( array(
				'menu' 	        => $args['name'],
				'menu_class'    => $args['class']
			));
}
add_shortcode('addmenu', 'diwp_menu_shortcode');


Bhuvi: Ok, I have added the code in my theme’s functions.php file. Now what next?

DIWP: Now add the shortcode [addmenu name=”Your Menu Name”] in your page or post or wherever you want to display menu in your WordPress website.

Bhuvi: Okay…but where can I find my menu name?

DIWP: Don’t worry…Man. I am here to help you. Just go to Appearance > Menu and find menu name as shown in the image below. Just copy that menu name from there and add it to your shortcode.

So in this case, it will be something like [addmenu name=”Primary Menu”]

create-menu-shortcode-in-wordpress

Bhuvi: Ok, I got it. Can I add class using this shortcode?

DIWP: Yes, you can add a class name for the menu by using attribute class=”your-class-name” in the shortcode.

Bhuvi: I think I got what I was looking for.

DIWP: Thanks, Keep Visiting Me DIVE IN WP. You will find really helpful information about WordPress.

Bhuvi: Yes.. Of Course I will.

DIWP: Thanks,

Advertisement

Leave a Reply

Your email address will not be published.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top