开发者

PHP Wordpress add class="last" to last item in menu list

I'm drawing out a listing of menu items inside a wordpress template (header.php) and need to assign a special className to the last menu item in the list. I'm building the list with this code...

$myposts = get_posts();
foreach($myposts as $post) :?> 
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>

I'd like to add this to the last menu item...

<li开发者_StackOverflow社区 class="last">...


You could try this (assuming get_posts() returns an array...)

<?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; ?>


You can add following code to functions.php file of your theme

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜