you can achieve this by manipulating the menu items array before it is rendered
function custom_menu_order($items, $args) {
// Check if this is the desired menu
if ($args->theme_location == 'primary') {
// Create your custom menu item
$custom_item = new stdClass();
$custom_item->ID = 'custom-item';
$custom_item->title = 'Custom Item';
$custom_item->url = '#';
$custom_item->menu_order = 3; // Set the order here
// Insert your custom menu item at the desired position
array_splice($items, 2, 0, array($custom_item));
}
return $items;
}
add_filter('wp_nav_menu_objects', 'custom_menu_order', 10, 2);
how you can see worked functionality above function perform
- Use the wp_nav_menu_objects filter to modify the menu items array.
- Find the position where you want to insert your custom menu item.
- Insert your custom menu item into the array at the desired position.
- Return the modified array