0

我希望在每个 ul 的最后 li 中添加一个类。例如,如果我有:

<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 函数实现这一点的任何想法?我已经看到成功针对第一个 ul li 的示例,但不要再深入了!

任何帮助将不胜感激。

干杯

4

2 回答 2

0

Add the below code to your 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');

This forces the extra markup to be added to the class list for the respective elements, rather than having more than one ID for a tag.

I think there should be a more elegant solution though.

于 2012-05-10T15:30:00.267 回答
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' );
于 2012-08-13T22:29:59.453 回答