WordPress: Programmatically Add Items to a Menu (Dynamically)

Menus are created and edited from in the WordPress backend and then called in frontend theme to be displayed by the wp_nav_menu() function. On some occasions, we may want to programmatically add one or two menu items to a menu because those menu items change frequently and it would be a chore to have to add / update them in the backend every time any of changes occur.

So how to programmatically add menu items to a WP menu on the fly?

For instance, what we have now in our theme as the top menu:

<ul id="main-nav" class="nav fl">
	<?php
	
	wp_nav_menu(array(
		'depth' => 6, 
		'sort_column' => 'menu_order', 
		'container' => 'ul', 
		'menu_id' => 'main-nav', 
		'menu_class' => 'nav fl', 
		'theme_location' => 'primary-menu', 
		'items_wrap' => '%3$s'
	));
	
	?>
</ul>

Firstly, we need to get the HTML returned by wp_nav_menu() by setting the parameter ‘echo’ => false. This way, we can get the menu HTML as a PHP variable and then manipulate it however we want. What I want to do is to add some sub menu items to the “Shop” item:

<ul id="main-nav" class="nav fl">
	<?php
	
	$my_wp_nav_menu = wp_nav_menu(array(
		'depth' => 6, 
		'sort_column' => 'menu_order', 
		'container' => 'ul', 
		'menu_id' => 'main-nav', 
		'menu_class' => 'nav fl', 
		'theme_location' => 'primary-menu', 
		'items_wrap' => '%3$s', 
		'echo' => false
	));
	
	$my_wp_nav_menu = str_replace(
		'>Shop</a></li>', 
		'>Shop</a><ul class="sub-menu">'.$my_sub_items_html.'</ul></li>', 
		$my_wp_nav_menu
	);
	
	echo $my_wp_nav_menu;
	
	?>
</ul>

The key is to insert a sub menu in there. In this case, I used the str_replace() function to do this. Make sure you use appropriate classes for <ul></ul> and <li></li> or they won’t be rendered as a sub menu.

$my_sub_items_html contains the sub menu items such as this:

<li class="menu-item menu-item-type-post_type menu-item-object-page"><a href="/product-category/bags/">Bags</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page"><a href="/product-category/accessories/">Accessories</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page"><a href="/product-category/toys/">Toys</a></li>

These can be dynamically generated from one of the taxonomies of your WordPress blog or you can specify your own.

1 thought on “WordPress: Programmatically Add Items to a Menu (Dynamically)”

Comments are closed.

Scroll to Top