如果您只想添加类.last
对于最后一个菜单项,这是一种更短的方法:
/**********************************************************/
/* add .last to last menu item */
/**********************************************************/
add_filter(\'wp_nav_menu\', \'add_last\');
function add_last($output) {
$output = substr_replace($output, \'class="last menu-item\', strripos($output, \'class="menu-item\'), strlen(\'class="menu-item\'));
return $output;
};
如果您还有子菜单,则可以使用以下代码(感谢
this article).
add_filter(\'wp_nav_menu\', \'add_last\');
function add_last($menuHTML) {
$last_items_ids = array();
// Get all custom menus
$menus = wp_get_nav_menus();
// For each menu find last items
foreach ( $menus as $menu_maybe ) {
// Get items of specific menu
if ( $menu_items = wp_get_nav_menu_items($menu_maybe->term_id) ) {
$items = array();
foreach ( $menu_items as $menu_item ) {
$items[$menu_item->menu_item_parent][] .= $menu_item->ID;
}
// Find IDs of last items
foreach ( $items as $item ) {
$last_items_ids[] .= end($item);
}
}
}
foreach( $last_items_ids as $last_item_id ) {
$items_add_class[] .= \' menu-item-\'.$last_item_id;
$replacement[] .= \' menu-item-\'.$last_item_id . \' last\';
}
$menuHTML = str_replace($items_add_class, $replacement, $menuHTML);
return $menuHTML;
};