我正在尝试找出如何在 while 循环输出的第一个和最后一个元素上添加第一个和最后一个类。我通过搜索发现的唯一一件事与直接使用 mysql 相关,而我在 Wordpress 循环中使用它(我放入了一个函数,我想在其中创建类 osu_first_last()
):
<div id="news-loop">
<h2 class="widget-title">News</h2>
<?php
// Build query for
$wp_news_query_temp = clone $wp_query;
$wp_news_query = new WP_Query();
$wp_news_query->query('category_name=News&showposts=3&orderby=date&order=DESC');
$news_counter = 0;
// Create posts loop
if ($wp_news_query->have_posts()) : while ($wp_news_query->have_posts()) : $wp_news_query->the_post(); ?>
<div class="news-entry news-entry-<?php echo $news_counter; ?><?php osu_first_last(); ?>">
<h3 class="entry-title">
<?php the_title(); ?>
</h3>
<?php twentyten_posted_dateonly(); ?>
<?php echo osu_short_excerpt(); ?>
</div> <!-- End div.news-entry -->
<?php
$news_counter++;
endwhile; ?>
<?php endif; $wp_query = clone $wp_news_query_temp; ?>
<a href="<?php bloginfo('url'); ?>/category/news/" class="sidebar-more">View all news</a>
</div>
有人可以建议最好的方法吗?
谢谢,
欧苏
最佳答案
您可以使用 current_post
和 post_count
并通过将其与查询一起传递给 osu_first_last() 来确定第一篇和最后一篇文章
然后像这样实现 osu_first_last()
function osu_first_last($query)
{
$extraClass = "";
if($query->current_post == 1)
{
$extraClass .= "first";
}
if($query->post_count == $query->current_post)
{
if($extraClass != "")
{
// post is first and last
$extraClass .= " ";
}
$extraClass .= "last";
}
return $extraClass;
}
在你的代码中它看起来像这样:
<div class="news-entry news-entry-<?php echo $news_counter; ?><?php echo osu_first_last($wp_news_query); ?>">
关于while循环中的PHP第一个和最后一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5868330/