我的循环返回五篇文章,HTML应该是这样的。。
<ul>
<li class="topfive"> ... </li>
<li class="topfive"> ... </li>
<li class="topfive"> ... </li>
<li class="topfive"> ... </li>
<li class="topfive"> ... </li>
</ul>
而且,我需要根据出现的顺序以编程方式向它们添加类,类似这样的。。
<ul>
<li class="topfive first"> ... </li>
<li class="topfive second"> ... </li>
<li class="topfive third"> ... </li>
<li class="topfive fourth"> ... </li>
<li class="topfive fifth"> ... </li>
</ul>
下面是我用来创建循环的代码:
function custom_top_products() {
$args = array (
\'post_type\' => \'products\',
\'post_status\' => \'publish\',
\'orderby\' => \'comment_count\',
\'posts_per_page\' => 5
);
$posts = new WP_Query( $args );
?>
<div id="topproducts" class="ratingbox">
<h3 class="rbh3">Top 5 Products</h3>
<div class="topproductcontainer">
<?php
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
?>
<li class="topfive"><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
} else {
echo \'<p class="trc">Sorry, No Popular Products Found</p>\';
}
wp_reset_postdata();
?>
</div>
</div>
<?php
}
请帮忙
最合适的回答,由SO网友:Eugene Manuilov 整理而成
只需使用类创建一个数组,并与主循环一起循环:
function custom_top_products() {
$classes = array( \'first\', \'second\', \'third\', \'fourth\', \'fifth\' );
$classes_count = count( $classes );
$posts = new WP_Query( array(
\'post_type\' => \'products\',
\'post_status\' => \'publish\',
\'orderby\' => \'comment_count\',
\'posts_per_page\' => 5
) );
$i = 0;
?><div id="topproducts" class="ratingbox">
<h3 class="rbh3">Top 5 Products</h3>
<div class="topproductcontainer"><?php
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
?><li class="topfive <?php echo $classes[$i++ % $classes_count] ?>">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</li><?php
}
wp_reset_postdata();
} else {
echo \'<p class="trc">Sorry, No Popular Products Found</p>\';
}
?></div>
</div><?php
}