2016-04-27 26 views
1

我需要這個for循環在WordPress中,但我認爲也是純PHP的。 我需要我的交替DIV,我somethink這樣的:PHP替代'受保護的'第一個元素

// 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

你能只是增加一個'浮動:left'」這些元素? – WillardSolutions

回答

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; ?>