ID, 'thumbn-6ren">
gpt4 book ai didi

php - 循环将 .last 类添加到循环中的最后一项

转载 作者:行者123 更新时间:2023-12-02 15:40:53 25 4
gpt4 key购买 nike

我使用 wordpress 并使用以下方法获取最近的 3 个帖子:

    <?php query_posts('showposts='.$latest_num.'&cat=-'.$featured_cat.','.$latest_ignore.''); ?>
<?php while (have_posts()) : the_post(); ?>
<li>
<div class="imgholder">
<a href="/wp-content/themes/twentyten/images/slide1.jpg" data-gal="prettyPhoto[featured]" title="<?php the_title(); ?>">
<img src="<?php echo get_post_meta($post->ID, 'thumbnail',true) ?>" width="275" height="145" alt="Post Image" class="postimg-s" />
</a>
</div>
<h4><?php the_title(); ?></h4>
<p><?php the_content('Read more...'); ?></p>
</li>
<?php endwhile; ?>

我想做的是添加一个名为 'last' 的类到 <li>元素在循环中的第 3 次交互。

有人知道我该如何添加这个吗?

最佳答案

在 while 循环外设置一个计数器

$count = 1;

检查该计数器的模数并根据需要输出类

<li <?php if(!$count % 3) echo 'class="last"; ?>>

在关闭循环之前增加你的计数器:

    $count++;
}

或者,应用于您的代码:

<?php 
$count = 1;
while (have_posts()) : the_post();
?>
<li <?php if(!$count % 3) echo 'class="last"; ?>>
<div class="imgholder">
<a href="/wp-content/themes/twentyten/images/slide1.jpg" data-gal="prettyPhoto[featured]" title="<?php the_title(); ?>">
<img src="<?php echo get_post_meta($post->ID, 'thumbnail',true) ?>" width="275" height="145" alt="Post Image" class="postimg-s" />
</a>
</div>
<h4><?php the_title(); ?></h4>
<p><?php the_content('Read more...'); ?></p>
</li>
<?php
$count++;
endwhile;
?>

模数条件的反直觉外观是,只要计数器可以被 3 整除,它就会返回 0。

关于php - 循环将 .last 类添加到循环中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6534353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com