如何在 Wordpress 中使用 wp_nav_menu() 在 <li> 中添加类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14464505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:08:54  来源:igfitidea点击:

How to add Class in <li> using wp_nav_menu() in Wordpress?

wordpress

提问by Ayyaz Zafar

I am using wp_nav_menu($args)and I want to add my_own_classCSS classname to the <li>element for getting the following result:

我正在使用wp_nav_menu($args)并且我想将my_own_classCSS 类名添加到<li>元素以获得以下结果:

<li class='my_own_class'><a href=''>Link</a>

How to do that?

怎么做?

采纳答案by Ennui

You can't add a class directly to the LIs very easily, but is there any reason not to target them in a slightly different but equally specific way (by their parent ul)?

您不能很容易地将一个类直接添加到 LI,但是否有任何理由不以稍微不同但同样具体的方式(通过它们的父级 ul)来定位它们?

You can set the class or ID of the menu with the menu_class and menu_id parameters (affixed to the UL parent of the LIs) and then target the li's via CSS that way, like so:

您可以使用 menu_class 和 menu_id 参数(附加到 LI 的 UL 父级)设置菜单的类或 ID,然后通过 CSS 以这种方式定位 li,如下所示:

<?php wp_nav_menu('menu_id=mymenu'); ?>

And for CSS:

对于 CSS:

ul#mymenu li {
    /* your styles here */
}

Edit: At the time of writing in 2013 this was the easiest way to add it, but updates since then have added the feature to add CSS classes directly in the admin navigation editor. See more recent answers for details.

编辑:在 2013 年撰写本文时,这是添加它的最简单方法,但此后的更新添加了直接在管理导航编辑器中添加 CSS 类的功能。有关详细信息,请参阅最近的答案。

回答by Andres F Garcia

You can add a filter for the nav_menu_css_classaction in your functions.php file.

您可以nav_menu_css_class在您的functions.php 文件中为操作添加过滤器。

Example:

例子:

function atg_menu_classes($classes, $item, $args) {
  if($args->theme_location == 'secondary') {
    $classes[] = 'list-inline-item';
  }
  return $classes;
}
add_filter('nav_menu_css_class', 'atg_menu_classes', 1, 3);

Docs: https://developer.wordpress.org/reference/hooks/nav_menu_css_class/

文档:https: //developer.wordpress.org/reference/hooks/nav_menu_css_class/

回答by Zunan

No need to create custom walker. Just use additional argument and set filter for nav_menu_css_class.

无需创建自定义步行者。只需使用附加参数并为 nav_menu_css_class 设置过滤器。

For example:

例如:

$args = array(
    'container'     => '',
    'theme_location'=> 'your-theme-loc',
    'depth'         => 1,
    'fallback_cb'   => false,
    'add_li_class'  => 'your-class-name1 your-class-name-2'
    );
wp_nav_menu($args);

Notice the new 'add_li_class' argument.

请注意新的“add_li_class”参数。

And set the filter on functions.php

并在functions.php上设置过滤器

function add_additional_class_on_li($classes, $item, $args) {
    if(isset($args->add_li_class)) {
        $classes[] = $args->add_li_class;
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);

回答by Rameez SOOMRO

HERE WordPress add custom class in wp_nav_menu links

这里WordPress 在 wp_nav_menu 链接中添加自定义类

OR you can add class <li class='my_own_class'><a href=''>Link</a></li>from admin panel:

或者您可以<li class='my_own_class'><a href=''>Link</a></li>从管理面板添加类 :

  1. Go to YOURSITEURL/wp-admin/nav-menus.php

  2. open SCREEN OPTIONS

  3. make checked CSS CLASSES, then you will see CSS Classes (optional)field in each menu link.
  1. YOURSITEURL/wp-admin/nav-menus.php

  2. 打开 SCREEN OPTIONS

  3. 进行检查CSS CLASSES,然后您将CSS Classes (optional)在每个菜单链接中看到字段。

回答by Regolith

use this filter nav_menu_css_classas shown below

使用此过滤器nav_menu_css_class,如下所示

function add_classes_on_li($classes, $item, $args) {
    $classes[] = 'nav-item';
    return $classes;
}
add_filter('nav_menu_css_class','add_classes_on_li',1,3);

UPDATE

更新

To use this filter with specific menu

在特定菜单中使用此过滤器

if ( 'main-menu' === $args->theme_location ) { //replace main-menu with your menu
    $classes[] = "nav-item"; 
}

回答by Trupti

Adding Class to <li>tag without editing functions.phpfile:

将 Class 添加到<li>标签而不编辑functions.php文件:

  1. Go to Appearance -> Menu -> Screen Options -> CSS Classes
  2. You will get CSS Class option enabled in Menu ItemsWindow
  1. 转到外观 -> 菜单 -> 屏幕选项 -> CSS 类
  2. 您将在Menu ItemsWindow 中启用 CSS Class 选项

enter image description here

在此处输入图片说明

回答by Mike

None of these responses really seem to answer the question. Here's something similar to what I'm utilizing on a site of mine by targeting a menu item by its title/name:

这些回答似乎都没有真正回答这个问题。这是类似于我在我的网站上通过按标题/名称定位菜单项而使用的内容:

function add_class_to_menu_item($sorted_menu_objects, $args) {
    $theme_location = 'primary_menu';  // Name, ID, or Slug of the target menu location
    $target_menu_title = 'Link';  // Name/Title of the menu item you want to target
    $class_to_add = 'my_own_class';  // Class you want to add

    if ($args->theme_location == $theme_location) {
        foreach ($sorted_menu_objects as $key => $menu_object) {
            if ($menu_object->title == $target_menu_title) {
                $menu_object->classes[] = $class_to_add;
                break; // Optional.  Leave if you're only targeting one specific menu item
            }
        }
    }

    return $sorted_menu_objects;
}
add_filter('wp_nav_menu_objects', 'add_class_to_menu_item', 10, 2);

回答by Amin

How about just using str_replacefunction, if you just want to "Add Classes":

str_replace如果您只想“添加类”,那么仅使用函数如何:

<?php
    echo str_replace( '<li class="', '<li class="myclass ',
        wp_nav_menu(
            array(
                'theme_location'    => 'main_menu',
                'container'         => false,
                'items_wrap'        => '<ul>%3$s</ul>',
                'depth'             => 1,
                'echo'              => false
            )
        )
    );
?>

Tough it is a quick fix for one-level menus or the menus that you want to add Classes to all of <li>elements and is not recommended for more complex menus

Tough 它是对单级菜单或要向所有<li>元素添加类的菜单的快速修复,不推荐用于更复杂的菜单

回答by Tamal Sarker

<?php
    echo preg_replace( '#<li[^>]+>#', '<li class="col-sm-4">',
            wp_nav_menu(
                    array(
                        'menu' => $nav_menu, 
                        'container'  => false,
                        'container_class'   => false,
                        'menu_class'        => false,
                        'items_wrap'        => '%3$s',
                                            'depth'             => 1,
                                            'echo'              => false
                            )
                    )
            );
?>

回答by Rovente

The correct one for me is the Zuan solution. Be aware to add isset to $args->add_li_class, however you got Notice: Undefined property: stdClass::$add_li_classif you haven't set the property in all yours wp_nav_menu()functions.

对我来说正确的是 Zuan 解决方案。请注意将 isset 添加到$args->add_li_class,但是Notice: Undefined property: stdClass::$add_li_class如果您尚未在所有wp_nav_menu()函数中设置该属性,则会得到。

This is the function that worked for me:

这是对我有用的功能:

function add_additional_class_on_li($classes, $item, $args) {
    if(isset($args->add_li_class)) {
      $classes[] = $args->add_li_class;
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);

回答by Atiqur R.

Without walker menuit's not possible to directly add it. You can, however, add it by javascript.

没有walker menu就不可能直接添加它。但是,您可以通过 javascript 添加它。

$('#menu > li').addClass('class_name');