简体   繁体   English

如何为Wordpress菜单锚添加唯一类?

[英]How to add unique class to Wordpress menu anchor?

I have this function : 我有这个function

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)
    $item_output = preg_replace('/<a /', '<a class="your-class" ', $item_output, 1);
    return $item_output;
}
add_filter('walker_nav_menu_start_el', 'my_walker_nav_menu_start_el', 10, 4);

Which is working fine, because it is setting a class on all my anchors in the menu. 一切正常,因为它正在菜单中所有anchors上设置一个类。 The problem is: it's setting the same class on all anchors. 问题是:它在所有锚点上都设置了相同的类。 I want different classes per anchor. 我想要每个锚定不同的类。 Is that possible? 那可能吗? If so, how can I do this? 如果是这样,我该怎么做?

Edit --> I want to have it like this: 编辑->我想要这样:

<li><a class="icon-bird"></a></li>
<li><a class="icon-book"></a></li>
<li><a class="icon-red"></a></li>

Assuming $item contains your values (bird, book, red, etc): 假设$item包含您的值(鸟,书,红色等):

function my_walker_nav_menu_start_el($item_output, $item, $depth, $args) {
    $item_output = preg_replace('/<a /', '<a class="item-' . $item . '"', $item_output, 1);
    return $item_output;
}
add_filter('walker_nav_menu_start_el', 'my_walker_nav_menu_start_el', 10, 4);

I used above code and make some changes and it's work for me , you can try with the below steps: 我使用了上面的代码并进行了一些更改,这对我来说是有效的,您可以尝试以下步骤:

you can follow the below Steps : 您可以按照以下步骤操作:

Step 1 : In the wp-admin, go to Appearance -> Menus,put the class on the menu item here "CSS Classes (optional)". 步骤1:在wp-admin中,转到外观->菜单,将类放在菜单项“ CSS类(可选)”中。 If you can't see the "CSS Classes (optional)" in the menu item, then there is "Screen Option" in the right top of the screen and there are the options "CSS Class" under "Show advanced menu properties" . 如果在菜单项中看不到“ CSS类(可选)”,则屏幕右上方有“屏幕选项”,而在“显示高级菜单属性”下有“ CSS类”选项

Step 2: Under your them folder/function.php add below code : 第2步:在您的他们folder / function.php下添加以下代码:

 function my_walker_nav_menu_start_el($item_output, $item, $depth, $args) {
    $class= $item->classes['0'];
    $item_output = preg_replace('/<a /', '<a class="'.$class.'"', $item_output, 1);
    return $item_output;
 }
add_filter('walker_nav_menu_start_el', 'my_walker_nav_menu_start_el', 10, 4);

Hope above code works for you , let me know if still it doesn't work. 希望上面的代码对您有用,让我知道它是否仍然无效。

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

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