WordPress - 如何将自定义类添加到子菜单 <ul>标签 [英] WordPress - How to add custom class to submenu <ul> tags

查看:21
本文介绍了WordPress - 如何将自定义类添加到子菜单 <ul>标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当创建自定义 WordPress 菜单并删除子菜单类时,默认值会重新添加,所以我只需要用我自己的类覆盖那些.下面的函数用于删除子菜单类,同时仅将自定义类添加到主要导航链接.

When creating a custom WordPress menu and removing submenu classes the defaults are added back in so I just need to overwrite those with my own classes. Below is the function that works to remove the submenu class while adding custom classes to only the primary nav links.

//Add Custom Class to Navigation <a> Tags
add_filter( 'nav_menu_link_attributes', 'add_class_anchor_nav_primary', 10, 3 );
function add_class_anchor_nav_primary( $atts, $item, $args ) {
    if ( (int) $item->menu_item_parent === 0 ) {
        $class         = 'dropdown submenu';
        $atts['class'] = $class;
    }

    return $atts;
}

推荐答案

因此,要修改子菜单的类,您有 2 个选项.第一个是使用 WordPress 使用的 Walker 来生成菜单.还有我更喜欢的解决方案二:

So to modify the class of your submenu you have 2 options. The first one is to use the Walker which is used by WordPress to generate the menu. And there is solution two which I prefer:

add_action('nav_menu_submenu_css_class', 'custom_submenu_css_class');
function custom_submenu_css_class() {
    return array('dropdown-menu');
}

这将用下拉菜单替换类子菜单.get 返回的数组可以有多个值.所以如果你想在你的子菜单中添加另一个类,你可以这样做:

This will replace the class sub-menu with dropdown-menu. The array which get's returned can have multiple values. So if you want another class in your submenu, you can do this:

add_action('nav_menu_submenu_css_class', 'custom_submenu_css_class');
function custom_submenu_css_class() {
    return array('class-1', 'class-2', 'class-3');
}

将此添加到您的 functions.php 文件中.我希望它有助于实现您的目标!

Add this to your functions.php file. I hope it helps to reach your goals!

这篇关于WordPress - 如何将自定义类添加到子菜单 &lt;ul&gt;标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆