簡體   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