PHP while 循环中的第一个和最后一个类
我正在尝试弄清楚如何在 while 循环输出的第一个和最后一个项目上添加第一个和最后一个类。我通过搜索发现的唯一一件事是与直接使用 mysql 相关,而我在 Wordpress 循环中使用它(我放入了一个函数,我想在其中创建类 osu_first_last()< /code>):
<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>
任何人都可以建议最好的方法吗?
谢谢,
奥苏
I'm trying to work out how to add a first and last class on the first and last items outputted from a while loop. The only thing I've found through searching has been relevant to working with mysql directly, while I'm using this in a Wordpress loop (I've put in a function where I want to create the class 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>
Can anyone advise on the best way to do this please?
Thanks,
osu
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
current_post
和post_count
并通过将其与查询一起传递给 osu_first_last() 来确定第一篇和最后一篇文章,然后像这样
在代码中 实现 osu_first_last()它看起来像这样:
ou can use the
current_post
andpost_count
and to determine the first and last post by passing it along with the query to osu_first_last()then implement osu_first_last() like this
In your code it would look like this:
使用
count($wp_news_query->posts)
您应该获得查询返回的帖子/页面数。使用$wp_news_query->current_post
您可以获得当前帖子/页面的索引(因此从 0 开始...)With
count($wp_news_query->posts)
you should get the number of post/page return by the query. And with$wp_news_query->current_post
you get the index of the current post/page (so starting with 0 ... )