![](/img/trans.png)
[英]Wordpress menu: Remove list-items and apply “.current-menu-item” to anchor tag
[英]add a class to anchor tag in current menu item in WordPress
function my_walker_nav_menu_start_el($item_output, $item, $depth, $args) {
$menu_locations = get_nav_menu_locations();
if ($item->menu_order == 1){
$item_output = preg_replace('/<a /', '<a class="active" ', $item_output, 1);
}
return $item_output;
}
add_filter('walker_nav_menu_start_el', 'my_walker_nav_menu_start_el', 10, 4);
上面的代碼將<a class="active">
放入第一個菜單項。 我只想將此類放在當前菜單項(所選菜單)上。
任何幫助都會很棒。
謝謝
對的,這是可能的。
您可以使用wp_nav_menu_objects過濾器來實現。
function my_wp_nav_menu_objects($objects, $args) {
foreach($objects as $key => $item) {
$objects[$key]->classes[] = 'my-class';
}
return $objects;
}
add_filter('wp_nav_menu_objects', 'my_wp_nav_menu_objects', 10, 2);
唯一的問題是,這些類將添加到li元素中,而不是直接添加到鏈接中。 但這是默認的WordPress行為,我不認為您應該更改它。
如果確實需要更改它,仍然可以:
function my_walker_nav_menu_start_el($item_output, $item, $depth, $args) {
// you can put your if statements in here (use item, depth and args in conditions)
if ( $depth == 1 ) {
$item_output = preg_replace('/<a /', '<a class="level-1-menu" ', $item_output, 1);
} else if ( $depth == 2 )
$item_output = preg_replace('/<a /', '<a class="level-2-menu" ', $item_output, 1);
}
// .. and so on
return $item_output;
}
add_filter('walker_nav_menu_start_el', 'my_walker_nav_menu_start_el', 10, 4);
檢查它在這里輸入鏈接描述
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.