3

I have some code that adds a menu item to a menu using wp_nav_menu_{$menu->slug}_items.

It's pretty easy to add a menu item as the first or last item of the menu, but I was wondering if there's any way to assign an order to the item, i.e. place it as the 3rd item in the menu.

If there's no method for that built into the filter, is there another way to achieve the same result?

1
  • The correct official way is to write your own Walker Class extension. Google for wp_nav_menu_walker on YT. Commented Nov 13, 2019 at 17:13

2 Answers 2

0

you can always search & replace by string or regex the output html of the filtered $items. anyway, if you're targeting usual menu items, you can add $post objects and order items through the wp_nav_menu_objects filter, otherwise here's the basic sample code:

function replace_itemcart_in_menu( $items, $args ) { 
    $url = home_url('my-item');
    $previtem = '<li id="menu-item-11" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-11"><a href="'.$carturl.'/">My Item</a>'; 
    $newitem = '<li>New Item</li>'; 
    $items = str_replace($previtem, $previtem.$newitem, $items); 
    return $items; 
}
0
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.