Dynamically add items to WordPress menus

With the help of the wp_get_nav_menu_items filter, you can easily add dynamic links to a WordPress menu without having to concatenate html strings, or write a custom nav walker.

This example shows how to use the filter and construct a pseudo menu-item object (to meet the expectations of a nav walker class) to add a dynamic “My Profile” link to an existing menu.

The first thing we need is a simple helper function that creates a menu item object according to WordPress’ expectations.

[pastacode lang=”php” manual=”%2F**%0A%20*%20Simple%20helper%20function%20for%20make%20menu%20item%20objects%0A%20*%20%0A%20*%20%40param%20%24title%20%20%20%20%20%20-%20menu%20item%20title%0A%20*%20%40param%20%24url%20%20%20%20%20%20%20%20-%20menu%20item%20url%0A%20*%20%40param%20%24order%20%20%20%20%20%20-%20where%20the%20item%20should%20appear%20in%20the%20menu%0A%20*%20%40param%20int%20%24parent%20-%20the%20item’s%20parent%20item%0A%20*%20%40return%20%5CstdClass%0A%20*%2F%20%0Afunction%20_custom_nav_menu_item(%20%24title%2C%20%24url%2C%20%24order%2C%20%24parent%20%3D%200%20)%7B%0A%20%20%24item%20%3D%20new%20stdClass()%3B%0A%20%20%24item-%3EID%20%3D%201000000%20%2B%20%24order%20%2B%20%24parent%3B%0A%20%20%24item-%3Edb_id%20%3D%20%24item-%3EID%3B%0A%20%20%24item-%3Etitle%20%3D%20%24title%3B%0A%20%20%24item-%3Eurl%20%3D%20%24url%3B%0A%20%20%24item-%3Emenu_order%20%3D%20%24order%3B%0A%20%20%24item-%3Emenu_item_parent%20%3D%20%24parent%3B%0A%20%20%24item-%3Etype%20%3D%20”%3B%0A%20%20%24item-%3Eobject%20%3D%20”%3B%0A%20%20%24item-%3Eobject_id%20%3D%20”%3B%0A%20%20%24item-%3Eclasses%20%3D%20array()%3B%0A%20%20%24item-%3Etarget%20%3D%20”%3B%0A%20%20%24item-%3Eattr_title%20%3D%20”%3B%0A%20%20%24item-%3Edescription%20%3D%20”%3B%0A%20%20%24item-%3Exfn%20%3D%20”%3B%0A%20%20%24item-%3Estatus%20%3D%20”%3B%0A%20%20return%20%24item%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

To use this helper function, you need to take advantage of the wp_get_nav_menu_items filter so we can add menu items as desired:

[pastacode lang=”php” manual=”add_filter(%20’wp_get_nav_menu_items’%2C%20’custom_nav_menu_items’%2C%2020%2C%202%20)%3B%0A%0Afunction%20custom_nav_menu_items(%20%24items%2C%20%24menu%20)%7B%0A%20%20%2F%2F%20only%20add%20item%20to%20a%20specific%20menu%0A%20%20if%20(%20%24menu-%3Eslug%20%3D%3D%20’menu-1’%20)%7B%0A%20%20%20%20%0A%20%20%20%20%2F%2F%20only%20add%20profile%20link%20if%20user%20is%20logged%20in%0A%20%20%20%20if%20(%20get_current_user_id()%20)%7B%0A%20%20%20%20%20%20%24items%5B%5D%20%3D%20_custom_nav_menu_item(%20’My%20Profile’%2C%20get_author_posts_url(%20get_current_user_id()%20)%2C%203%20)%3B%20%0A%20%20%20%20%7D%0A%20%20%7D%0A%20%20%20%20%0A%20%20return%20%24items%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

That’s it! To create a hierarchy (dropdown) of menu items, you could write your hook like this:

[pastacode lang=”php” manual=”add_filter(%20’wp_get_nav_menu_items’%2C%20’custom_nav_menu_items2’%2C%2020%2C%202%20)%3B%0A%0Afunction%20custom_nav_menu_items2(%20%24items%2C%20%24menu%20)%20%7B%0A%20%20if%20(%20%24menu-%3Eslug%20%3D%3D%20’menu-1’%20)%20%7B%0A%20%20%20%20%24top%20%3D%20_custom_nav_menu_item(%20’Top%20level’%2C%20’%2Fsome-url’%2C%20100%20)%3B%0A%0A%20%20%20%20%24items%5B%5D%20%3D%20%24top%3B%0A%20%20%20%20%24items%5B%5D%20%3D%20_custom_nav_menu_item(%20’First%20Child’%2C%20’%2Fsome-url’%2C%20101%2C%20%24top-%3EID%20)%3B%0A%20%20%20%20%24items%5B%5D%20%3D%20_custom_nav_menu_item(%20’Third%20Child’%2C%20’%2Fsome-url’%2C%20103%2C%20%24top-%3EID%20)%3B%0A%20%20%20%20%24items%5B%5D%20%3D%20_custom_nav_menu_item(%20’Second%20Child’%2C%20’%2Fsome-url’%2C%20102%2C%20%24top-%3EID%20)%3B%0A%20%20%7D%0A%0A%20%20return%20%24items%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

Be careful. It’s important that no menu items share the same menu_order property.

Finally, I’ve created a class and example of its usage as a GitHub Repo: WordPress class to add custom menu items dynamically.  See the first comment on the gist for usage examples.

[pastacode lang=”php” user=”daggerhart” repos=”wp-custom-menu-items” path_id=”custom-menu-items.php” revision=”” highlight=”” lines=”” provider=”github”/]

20 Thoughts


Janos Ver
November 21, 2015

Thanks for this article. I have found it very useful. The only thing I’d like to add is that I discovered it today that once I added the above code to my site to replace a menu item based on user action broke the Appearance-> Customize menu and I got an error (Exception) saying some properties are missing. By looking at the object definition at https://developer.wordpress.org/reference/functions/wp_setup_nav_menu_item/ and the error message itself I figured out that the following were missing from _custom_nav_menu_item function (header and return just added to provide some context):

function _custom_nav_menu_item( $title, $url, $order, $parent = 0 ){

$item->target = ”;
$item->attr_title = ”;
$item->description = ”;
$item->xfn = ”;
$item->status = ”;

return $item;

I hope it saves some time and headache for others looking to use this filter.

Jonathan Daggerhart
November 21, 2015

Thanks Janos, I’ve updated the post.

Dave Spencer
December 17, 2015

I too found this useful. Care to expand it to so as to be able to create a menu with submenus? I would like to be able to inject an item in to the menu bar that has a dropdown with submenus below it. Just a thought – it would make this the ultimate guide!

Jonathan Daggerhart
December 30, 2015

Hi Dave,

I’ve updated the post to show how to create submenu items. Note: I had to make a small update to the “_custom_nav_menu_item” function (db_id) for this to work.

Let me know how it goes!

December 23, 2015

Thanks for this snippet, just an small issue in your helper

$item->menu_parent_item = $parent;

should be

$item->menu_item_parent = $parent;

Jonathan Daggerhart
December 30, 2015

Thanks for the heads up! I’ve corrected the error in the post.

June 29, 2016

Thank you very much for your article.
I create some pages dynamically using a PhP file. Adding your code at the beginning of the file, the page is correctly inserted in the menu but it’s not highlighted in menu and breadcrumb is not correct?
Any idea ?

August 31, 2016

Jonathan, thanks a lot for this information.

I’m using your article to try and SUCCESSFULLY create sub-menu items with this changes and specifying an already created parent item:

function _custom_nav_menu_item( $title, $url, $order, $parent = 0 ){
$item = new stdClass();
$item->ID = 1000000 + $order + parent;
$item->db_id = $item->ID;
$item->title = $title;
$item->url = $url;
$item->menu_order = $order;
$item->menu_item_parent = PARENT_MENU_ITEM_ID;//$parent;
$item->type = ”;
$item->object = ”;
$item->object_id = ”;
$item->classes = array();
$item->target = ”;
$item->attr_title = ”;
$item->description = ”;
$item->xfn = ”;
$item->status = ”;
return $item;

add_filter( ‘wp_get_nav_menu_items’, ‘custom_nav_menu_items2’, 20, 2 );

function custom_nav_menu_items2( $items, $menu ) {
if ( $menu->slug == ‘menu-1’ ) {
//$top = _custom_nav_menu_item( ‘Top level’, ‘/some-url’, 100 );

//$items[] = $top;
//$items[] = _custom_nav_menu_item( ‘First Child’, ‘/some-url’, 101, $top->ID );
//$items[] = _custom_nav_menu_item( ‘Third Child’, ‘/some-url’, 103, $top->ID );
//$items[] = _custom_nav_menu_item( ‘Second Child’, ‘/some-url’, 102, $top->ID );
// the query
$wpb_all_query = new WP_Query(array(‘post_type’=>’custom_post_type_name’, ‘post_status’=>’publish’, ‘posts_per_page’=>-1, ‘orderby’ => ‘title’, ‘order’ => ‘ASC’));
if ( $wpb_all_query->have_posts() ) :
$subposition = 201;
while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post();
// get the custom post data
$title = get_the_title();
$slug = basename(get_permalink());
// create the menu sub item
$items[] = _custom_nav_menu_item( $title, ‘/’.$slug, $subposition++, $top->ID );
else :
echo ”. _e( ‘Sorry, no posts matched your criteria.’ ).”;

return $items;

Working great!

August 31, 2016

Hi again, the only problem I’ve found is that a “The given object ID is not that of a menu item.” error shows up when saving the menu from /wp-admin/nav-menus.php

Any suggestion?

August 23, 2017

I’m trying to use your class in a plugin i’m working on but i got some errors.
here’s the relevant code samples:
inside my main plugin file:

add_action('wp_loaded', function () {
//that's the method that runs our code inside:

here’s the static function definition:

public static function creaWPMenuItems()
        $menuTree = ['node'=>['parentMenu'=>'menu-1',
                              'text'=>'text menu item 1',
      foreach ($menuTree as $menuNode) {
          custom_menu_items::add_item($menuNode['parentMenu'], $menuNode['text'], $menuNode['url'], $menuNode['id']);

the item gets created and correctly displayed but then, whene i try to edit the menu from wp-admin/nav-menus.php i got the following errors and edits do not get saved:

E_NOTICE  Undefined property: stdClass::$post_excerpt - /vagrant/wp_clean/wp-content/themes/Avada/includes/class-avada-nav-walker-megamenu.php:166 
#5 /vagrant/wp_clean/wp-includes/class-wp-walker.php:146 - Avada_Nav_Walker_Megamenu->start_el('			display_element(stdClass, Array[0], 0, 0, Array[1], '			walk(Array[5], 0, stdClass)
#2 /vagrant/wp_clean/wp-admin/includes/nav-menu.php:958 - walk_nav_menu_tree(Array[5], 0, stdClass)
#1 /vagrant/wp_clean/wp-admin/nav-menus.php:496 - wp_get_nav_menu_to_edit(3)

Do you have any suggestions?


Jonathan Daggerhart
August 23, 2017

Hi Lorenzo,

I haven’t run into this issue, but it seems you and plenty others have. In an attempt to fix this, I’ve updated the gist to now only execute on the frontend. I can’t really think of a reason why it should need to happen on the backend Dashboard, so hopefully this is a good fix.

If you get a chance to re-copy the gist and test it out, please let me know if it fixes the problem.


August 23, 2017

Thanks! I’ll update and let you know asap :)

August 23, 2017

The fix seems to work well, also the fact of not seeing the items in the dashboard is much more tidy.
Thanks a lot!

February 24, 2018

Thanks a lot!!!!
I was deseperate trying to do it, and thanks to your post, it was really easy!!

June 22, 2018

Thank you so much for this article. It saved lot of my time and efforts finding and implementing this.

September 1, 2018

SUPERB!!! Best code i could find for this !!! ;)

Luyen Dao
February 12, 2019

Hi, thank you for this – is it possible to add children to the sub-menu?

Parent Menu
— Child Level 1
—- Child Level 2
—- Child Level 2

I have a use case where I need to list posts (Child Level 2) by a taxonomy term (Child Level 1). My guess is that if I can reference Child Level 1 as a “parent ID”…i could do so, but not sure how. Any suggestions are greatly appreciated.

March 15, 2019

I tried the same, but it did not work.
Would love to have child level 2 menu :-)

any suggestions?

October 7, 2019

If you\’re still trying to figure out how to do this, it\’s actually really simple! I needed three levels for a menu and this is the final parameter (@param null ID).

custom_menu_items::add_item( 'menu-1', 'Child 2', '/some-url/child-2', 0, 123456, 987654321 );
custom_menu_items::add_item( 'menu-1', 'Child 3', '/some-url/child-3', 0, 987654321 );

By passing in ID 987654321 to ‘Child 2’, I was able to use that as the $parent param for ‘Child 3’ which appears as a child of Child 3.

January 2, 2020

Kyle, thank you for providing how you were able to make the 3 level drop down menu. I followed your instructions and unfortunately I\’m not having any luck with this. Jonathan this is AWESOME! Thanks for all of your work! You helped me tremendously! If I can get the 3-level menu I\’ll be even happier. :-)

January 2, 2020

Alright I figured it out. I am using Bootstrap Navwalker for the menu and eventually realized that was the problem. I had to do the following to make it work:

1. Pass in the class of \’has-children\’ as an attribute:

custom_menu_items::add_item( \’menu-1\’, \’Child 2\’, \’/some-url/child-2\’, 0, 123456, 987654321, \’has-children\’ );

2. Modify \”depth\” value in Navwalker when you call wp_nav_menu.

\’depth\’ => 3,

3. Add the javascript on page load:

//for menu
jQuery(\’.dropdown-menu > li > .dropdown-menu\’).parent().addClass(\’dropdown-submenu\’).find(\’ > .dropdown-item\’).attr(\’href\’, \’javascript:;\’).addClass(\’dropdown-toggle\’);
jQuery(\’.dropdown-submenu > a\’).on(\”click\”, function(e) {
var dropdown = jQuery(this).parent().find(\’ > .show\’);
jQuery(\’.dropdown-submenu .dropdown-menu\’).not(dropdown).removeClass(\’show\’);
jQuery(\’.dropdown\’).on(\”hidden.bs.dropdown\”, function() {

4. Add this to your style.css. After you\’re sure it\’s working, modify it to meet the look you want for your theme.

.dropdown-submenu {
position: relative;
.dropdown-submenu .dropdown-menu {
top: 0; left: 95%; margin-top: -1px;
@media (max-width: 992px)
.dropdown-menu {
padding: .5rem 0;
margin: .125rem 0 0;
li > ul > li > ul > li > .dropdown-item {
padding: .25rem 3rem;
li > ul > li > ul > li > .dropdown-item:before {
content: \’• \’;

March 7, 2019

Hi, thanks for this (in the meantime) “old” posting, it helped a lot.

But with php 7.1 you have to do some “Dr. Jekyll to Mr. Hyde Typecasting” in the helper function like this to avoid warnings.

In line 12 of the avove given code change

$item->ID = 1000000 + $order + parent;
$item->ID = 1000000 + (int)$order + (int)’parent’;

Carlos Alberto
July 10, 2019

Thanks Bro!!!! Found your article was so nice. Keep on the line

Barush Lakshman
August 29, 2019

Excellent informtion, thanks! Quick question: In the helper function you describe the 4th parameter as:
* @param int $parent – the item\\\’s parent item
So… how do you determine what value to pass as the \\\”parent item\\\”? (Sorry if that\\\’s a dumb question!)

Ömür Yanıkoğlu
April 27, 2020

This is just great! Thank you :)

Randy Abidin
July 18, 2020

Thank you so much for this. I’ve been wanting to programmatically create custom menus for a couple years now!!!
I’ve created a WP plugin based on your work at https://github.com/rabidin/dynamic-menus.
It allows the admin to control the display of the menus based on start/end times, is/is not logged in, is/is not front & Home page, URL parameters.

One of the issues I am having is I cannot get it to work in the footer. I am somewhat of an intermediate PHP programmer and i just cannot figure it out. I loaded your original GitHub code to verify it is not an issue with my code and it did not work in footer.

Any help/insight would be really appreciated!

Muhammad Zaheer Dad
October 7, 2020

To work with custom post types change line # 138
From : if ($object_type == \\\’post\\\’ && $object = get_post( $object_ID ) ) {

To: if (post_type_exists($object_type) && $object = get_post( $object_ID ) ) {

August 3, 2021

excellent, thank you!

Iurie Malai
August 26, 2021

I suppose the line “$item->ID = 1000000 + $order + parent;” must be “$item->ID = 1000000 + $order + $parent;”. Or not?

Jonathan Daggerhart
October 5, 2021

Yes! Thanks for pointing that out. I’ve fixed it.

November 4, 2021

Hi there,
This is really excellent. Thank you SO much. The issue I’m having is with the item order. I want to add these items to the beginning of my nav bar, not the end. But when I try to put an order number of 1 or 2, it over-writes the first item in my nav. Any ideas what I can do to solve this?

Jonathan Daggerhart
November 4, 2021

Hi Laura,

I haven’t tried that personally, but I wouldn’t be surprised if you could use negative numbers. Have you tried setting the order to -1?

November 4, 2021

Yeah. I should have mentioned that I tried negative numbers. The items stay at the end when doing that. Interestingly, if I give them a number of 2 or above, the items are just inserted into the nav bar as directed, without any issues except that they’re in the wrong place. If I make the order number 1, it over-writes the first item in my nav. Such an odd behavior. I’m not sure how to solve this.

Jonathan Daggerhart
November 4, 2021

This might sound like a weird idea, but you could make the first item in the menu something you plan to overwrite. A placeholder. Then have your dynamic menu item code replace it when appropriate, or remove it in cases where the menu item shouldn’t show up.

It’s been a while since I’ve used this functionality on a site. If that idea doesn’t work for you, I’d have to tinker with it a bit to come up with something else.

November 5, 2021

Hi there,
Yeah. Tried that. Then noticed that I’m getting this error when I try to make any changes to my nav bar: “The given object ID is not that of a menu item.”

November 5, 2021

So, what I ended up doing was to add a whole new menu just before the main nav. And I targeted that one with this script. It worked like a charm :)

Leave a Reply

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