
[英]How to add a specific class to the first post in a custom loop in Wordpress
[英]Wordpress Loop, Add specific class to the 2nd post, 3rd, reset, add class etc
我試圖自定義自定義帖子類型並根據帖子的順序更改輸出。 我在下面有以下內容,但訂單輸出正常運行
輸出如下所示(在前3個帖子之后跳過):
我希望它像這樣出來:
約翰·杜(John Doe),古董伯班克(Vintage Burbank)1兩
<?php $args = array( 'post_type' => 'testimonials', 'posts_per_page' => -1 ); $query = query_posts($args); ?> <?php $i = 1; while (have_posts()) : the_post(); ?> <?php if($i%3 == 0) : ?> <?php the_title();?> three <?php elseif($i%2 == 0) : ?> <?php the_title();?> two <?php else : ?> <?php the_title();?> <?php endif; ?> <?php $i++; ?> <?php endwhile;?> <?php wp_reset_query(); ?>
為什么到處使用? 另外,當您獲得匹配項時,您需要重置$ i,它應該可以工作。 嘗試這個:
<?php
$args = array(
'post_type' => 'testimonials',
'posts_per_page' => -1
);
$posts = get_posts($args);
$i = 1;
foreach ($posts as $post) {
setup_postdata($post);
if($i%3 == 0) {
echo get_the_title().' three';
$i = 0;
}
elseif($i%2 == 0) {
echo get_the_title().' two';
$i = 0;
}
else {
the_title();
}
$i++;
}
wp_reset_postdata();
?>
好的,我認為您的代碼還可以,唯一的問題是您對$i
更新很差。 我已經修改了您的代碼,並且我認為它應該可以工作(如果不行,請通知我)。
<?php
$args = array(
'post_type' => 'testimonials',
'posts_per_page' => -1
);
$query = query_posts($args);
?>
<?php $i = 1;
while (have_posts()) : the_post(); ?>
<?php if ($i % 3 == 0) : ?>
<?php the_title(); ?> three
<?php elseif ($i % 2 == 0) : ?>
<?php the_title(); ?> two
<?php else : ?>
<?php the_title(); ?>
<?php endif; ?>
<?php /* Comment this line */ ?>
<?php /* $i++; */?>
<?php /* Add this one */ ?>
<?php $i = ($i >= 3) ? 1 : ($i + 1); ?>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.