繁体   English   中英

PHP Wordpress将class =“ last”添加到菜单列表中的最后一项

[英]PHP Wordpress add class=“last” to last item in menu list

我要在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">...

您可以尝试此操作(假设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; ?>

您可以将以下代码添加到主题的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;
}

暂无
暂无

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

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