How to add menu Item programmatically in WordPress?

If you developing a plugin or theme and want to set your custom page directly in the active WordPress Menu. are you struggling to find the answer for How to add menu item programmatically in WordPress? then this post will be helpful for you.  In this post, I am going to explain and give more information about WordPress functions for adding different kind of menu items in different kind of created WordPress Menus.

WordPress Menu List:

All Created menu in WordPress gets stored as a term of taxonomy `nav_menu` in WordPress Database.
so there are two way to get the list of all menus
1. $menu_lists =  get_terms( ‘nav_menu’, $args)
2. $menu_lists = wp_get_nav_menus();

Add a page as Menu Item With Code:

Suppose your plugin/theme create a custom page that you want to add directly in menu on plugin and theme activation.

we can use WordPress Function wp_update_nav_menu_item

The above code will add the specified page/post mention in the $_post_id in the menu mention in $_menu_id.

You can explore more about different param of args of this functions here

Add a Custom link as Menu Item with code

Suppose you want to add an external link as the menu item using code.
you can use same wp_update_nav_menu_item  function but here the param will be bit different

 

following are the default param of  function

$defaults = array(
        'menu-item-db-id'       => $menu_item_db_id, // menu item ID, If exist.
	'menu-item-object-id'   => 0, // menu item to add.
	'menu-item-object'      => '', // post type, taxonomy - post or term belong to.
	'menu-item-parent-id'   => 0, // parent menu id.
	'menu-item-position'    => 0, // item position in menu.
	'menu-item-type'        => 'custom',// post_type, post_type_archive, taxonomy, custom.
	'menu-item-title'       => '', // custom title of the menu item.
	'menu-item-url'         => '', // custom url of menu item.
	'menu-item-description' => '', // menu item description.
	'menu-item-attr-title'  => '', // menu item attribute title.
	'menu-item-target'      => '', // _blank, to open link on new tab.
	'menu-item-classes'     => '', // menu item extra custom class.
	'menu-item-xfn'         => 'friend', // to set XHTML Friends Network. it will set rel attribute to your link, ex. rel=`friend` to set that link is your friends blog or so.
	'menu-item-status'      => '', // draft, publish.
);

I hope this article helps anyone. If you like it or it helps you,  please give a small time to comment and share your thought, Question or suggestions.

It will encourages me 🙂  …. Thank You :=)

2 Replies to “How to add menu Item programmatically in WordPress?

Leave a Reply

Your email address will not be published. Required fields are marked *