我在wordpress模板(header.php)中列出了一个菜单项列表,需要为列表中的最后一个菜单项指定一个特殊的className。我正在使用此代码构建列表...
$myposts = get_posts();
foreach($myposts as $post) :?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
我想将其添加到最后一个菜单项...
<li class="last">...
答案 0 :(得分:1)
你可以尝试这个(假设get_posts()返回一个数组......)
<?php
$myposts = get_posts();
$last_key = end(array_keys($array));
foreach($myposts as $key => $post) :
?>
<li <?php if ($key==$last_key) echo 'class="last"'; ?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
答案 1 :(得分:0)
您可以将以下代码添加到主题的functions.php文件中
add_filter( 'wp_nav_menu_objects', 'first_last_class_to_top_level_menu' );
function first_last_class_to_top_level_menu( $objects ) {
// add 'first' class to first element of menu items array
$objects[1]->classes[] = 'first';
// find array index of the last element of top level menu
foreach($objects as $i=>$item) if($item->menu_item_parent==0) $last_top_level_menu_index = $i;
// add 'last' class to the last element of top level menu
$objects[$last_top_level_menu_index]->classes[] = 'last';
return $objects;
}