Function to insert items into a WordPress menu by Menu ID at any position!

I recently needed to dynamically insert a menu item into a specific menu programmatically.

Almost every solution out there required targetting the menu by its menu location however my menu was not assigned a menu location under “Appearance > Menus” and I wanted to find a way to target the menu by its slug or menu ID.

The information was out there to find but not particularly well documented so I figured I’d share my eventual solution:

add_filter('wp_nav_menu_items','custom_menu_item', 10, 2);
function custom_menu_item($menu, $args){
	if($args->menu == '64849'):
		return $menu."<li><a href="#">My Menu Item</a></li>";
    return $menu;

This function, inserted into my theme function.php file allows me to target my specific menu ID (64849) and then append an item into the end of the menu.

While achieving my basic goal, I realized that if a situation arose where I needed to insert an item in a specific position, this code wouldn’t work.

What if I need to insert a menu item at the start of the menu? Or in a specific position?

Accomplishing this is a little more complicated but I did eventually solve the problem.

I built a function to capture menu items into an array, then utilizing an array_splice to insert our menu item.

Utilizing an array_splice allows us to insert an item into the array at any position so it gives us the control we need to insert a menu item wherever we want:

function insert_menu_item($items, $args){
	// Target menu by ID
	if($args->menu == '64849'){
		// Build empty array
		$items_array = array();
		while(false !== ($item_pos = strpos($items, '<li', 3))){
			// Insert existing menu items into array
			$items_array[] = substr($items, 0, $item_pos);
			$items = substr($items, $item_pos);
		$items_array[] = $items;
		// Utilize array splice to insert our menu item at position 0
		array_splice($items_array, 0, 0, '<li><a href="#">My Menu Item</a></li>');
		$items = implode('', $items_array);
    return $items;
add_filter('wp_nav_menu_items', 'insert_menu_item', 10, 2);

The second argument value on the array_splice dictates the position to insert our menu item, so for example, changing the array_splice as follows would insert our custom menu item after the second item:

array_splice($items_array, 0, 2, '<li><a href="#">My Menu Item</a></li>');

In this way, you can inject a menu item as any position into a specific menu ID.

Questions? Comments?

Let me know below in the comments.

Leave a Reply

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