简体   繁体   English

在WordPress当前菜单项中添加一个类来锚定标签

[英]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);

The code above puts an <a class="active"> to the first menu item. 上面的代码将<a class="active">放入第一个菜单项。 I want to put this class only to current menu item (the selected menu). 我只想将此类放在当前菜单项(所选菜单)上。

any help would be great. 任何帮助都会很棒。

Thanks 谢谢

Yes, it is possible. 对的,这是可能的。

You can achieve this using wp_nav_menu_objects filter. 您可以使用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);

The only problem is that these classes will be added to li elements and not to links directly. 唯一的问题是,这些类将添加到li元素中,而不是直接添加到链接中。 But it's default WordPress behavior and I don't think you should change it. 但这是默认的WordPress行为,我不认为您应该更改它。

If you really have to change it, it is still possible: 如果确实需要更改它,仍然可以:

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);

Check it enter link description here 检查它在这里输入链接描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM