偶数/奇数帖子的Wordpress循环

时间:2013-09-26 18:01:11

标签: php wordpress loops

我有两列,我希望一个帖子类型均匀分配到每个列。所以这是两个并排的div,我想要:

Div1 = Post1,Post3,Post5

Div2 = Post2,Post4,Post6

所以基本上得到奇数/偶数帖子。不完全确定如何做到这一点。

<?php query_posts('post_type=post-type'); ?>
<?php if (have_posts()) : ?>  
<?php while (have_posts()) : the_post(); ?>  

<div class="column1">
<?php 
  //Get Odd Posts
?>
</div>

<div class="column2">
<?php 
  //Get Even Posts
?>
</div>

 <?php endwhile; ?>  
<?php else : ?>  
//Something that happens when a post isn’t found.  
<?php endif; ?>  

2 个答案:

答案 0 :(得分:1)

要做你想做的事情,首先你必须将结果存储在某处(偶数/奇数),然后显示它们。

虽然你应该用CSS而不是PHP来定位这些帖子,因为它最多只是hackish。

<?php query_posts('post_type=post-type'); ?>
<?php if (have_posts()) : ?>  
    <?php
        $i = 0;

        while (have_posts())
        {
            $key = $i & 1 ? 'odd' : 'even';

            $post[$key] = array(get_the_title() => get_the_content());

            $i++;
        }
    ?>
    <div class="column1">
        <?php foreach ($post['even'] as $title => $content) : ?>
            <?php echo $title; ?>
            <?php echo $content; ?>
        <?php endforeach; ?>
    </div>
    <div class="column2">
        <?php foreach ($post['odd'] as $title => $content) : ?>
            <?php echo $title; ?>
            <?php echo $content; ?>
        <?php endforeach; ?>
    </div>
<?php else : ?>  
    //Something that happens when a post isn’t found.  
<?php endif; ?>

答案 1 :(得分:0)

你想使用模数运算符,如下所示:

<?php
$i = 0;

for ($i = 0; $i <20; $i++){
    $class = $i % 2 == 0 ? "even" : "odd";
    echo "<div class='" . $class . "'>";

    echo "</div>";
}
?>