我在WordPress中需要这个循环,但我认为纯PHP也可以。 我需要替换我的DIV,我有这样的想法:
// Here I getting total count of posts - return as INT, ex. 4
$countOffers = wp_count_posts( 'offer' )->publish;
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if ( $countOffers % 2 == 0 ): ?>
// Align to left side
<?php get_template_part( 'template-parts/Offer/content', 'left' ); ?>
<?php else: ?>
// Align to right side
<?php get_template_part( 'template-parts/Offer/content', 'right' ); ?>
<?php endif ?>
<?php $countOffers--; ?>
<?php endwhile; ?>
它工作正常但是我想在左侧“保护”第一个元素 这意味着无论我返回多少项,它总是第一个在左边。
答案 0 :(得分:1)
为此使用计数器变量(在此示例中为$counter
)。在while
循环的每次迭代中,检查$counter
是否可被2整除,并相应地对齐元素。
您的代码应该是这样的:
$countOffers = wp_count_posts( 'offer' )->publish;
$counter = 1;
<?php while ($the_query->have_posts() && $counter <= $countOffers) : $the_query->the_post(); ?>
<?php if ( $counter % 2 != 0 ): ?>
// Align to left side
<?php get_template_part( 'template-parts/Offer/content', 'left' ); ?>
<?php else: ?>
// Align to right side
<?php get_template_part( 'template-parts/Offer/content', 'right' ); ?>
<?php endif ?>
<?php ++$counter; ?>
<?php endwhile; ?>