2012-05-10 139 views
0

我正在寻找为每个ul的最后一个li添加一个类。因此,举例来说,如果我有:通过wp_nav_menu_items向Wordpress菜单添加类

<ul> 
    <li></li> 
    <li> 
     <ul> 
     <li></li> 
     <li></li> 
     </ul> 
    </li> 
</ul> 

我想添加一个过滤器,使这个:

<ul> 
    <li></li> 
    <li class="last"> 
     <ul> 
     <li></li> 
     <li class="last"></li> 
     </ul> 
    </li> 
</ul> 

如何用PHP函数来实现这一目标的任何想法?我已经看到了成功瞄准第一个ULLI的例子,但是不要再深入了解这个!

任何帮助将不胜感激。

干杯

+0

这是否帮助? http://webknight-nz.blogspot.ca/2009/04/styling-first-and-last-list-items-and.html – anuragbh

回答

0

下面的代码添加到您的functions.php

function add_first_and_last($output) { 
    $output = preg_replace('/class="menu-item/', 'class="first-menu-item menu-item', $output, 1); 
    $output = substr_replace($output, 'class="last-menu-item menu-item', strripos($output, 'class="menu-item'), strlen('class="menu-item')); 
    return $output; 
} 
add_filter('wp_nav_menu', 'add_first_and_last'); 

这迫使额外的标记将被添加到类列表中各个元素,而不是一个以上的ID一个标签。

我认为应该有更优雅的解决方案。

+0

感谢您的答复利宾。但我不相信这会为嵌套列表添加标记。你能确认这是否针对儿童ul? – BIOS

0

自从发布这个问题已经有一段时间了,但我一直在寻找嵌套列表项问题的答案,并且无法在任何地方找到它(只是一级列表的解决方案)。所以我想出了这个,这似乎工作,但感觉有点笨重。但无论如何,这个添加到您的functions.php:

function add_last_item_class($items) { 
    $ar_index = array(); 
    // loop through all the items and save the index of the last item belonging to a specific parent 
    for ($i = 1; $i <= count($items); $i++): 
    $ar_index[$items[$i]->menu_item_parent] = $i; 
    endfor; 
    // loop through the saved indexes and add the class 'last' to each of them 
    foreach($ar_index as $last_index): 
    $items[$last_index]->classes[] = 'last'; 
    endforeach; 
    return($items); 
} 
add_filter('wp_nav_menu_objects', 'add_last_item_class');