admin管理员组文章数量:1122832
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?
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?
Share Improve this question edited May 24, 2013 at 21:55 s_ha_dum 65.5k13 gold badges84 silver badges174 bronze badges asked May 24, 2013 at 21:51 Jeremiah PrummerJeremiah Prummer 8224 gold badges13 silver badges26 bronze badges 1- The correct official way is to write your own Walker Class extension. Google for wp_nav_menu_walker on YT. – user3135691 Commented Nov 13, 2019 at 17:13
2 Answers
Reset to default 0you 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;
}
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
本文标签: filtersSet Item Order with wpnavmenumenugtslugitems
版权声明:本文标题:filters - Set Item Order with wp_nav_menu_{$menu->slug}_items 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736295260a1929532.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论