WordPress根据ID循环奇数的帖子,然后根据ID循环偶数的帖子


WordPress loop odd numbered posts based on ID and then even posts based on ID

我需要只显示奇数的WordPress POST ID,然后只显示偶数的POST ID。

是否有一种方法来修改我的当前代码下面,这样我就可以运行两个循环一个只是显示一个奇数ID和一个显示一个偶数ID的帖子?

<!-- loop posts -->
<?php $loop = new WP_Query(array('post_type' => 'post', 'posts_per_page' => -1, 'orderby'=> 'DESC'));
while ( $loop->have_posts() ) : $loop->the_post();
$postLink = get_post_meta($post->ID, "postLink", true);
$classes = array(
    'blogOverviewLoop',
    'col06',
    'darkGrey'
    );
?>
<div <?php post_class( $classes ); ?>>
    <article>
        <?php get_template_part( 'pf', get_post_format() ) ?>
    </article>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>

您应该能够使用get_posts:

//Arguments
$args = array('post_type' => 'post', 'posts_per_page' => -1, 'orderby'=> 'DESC');
//Get posts with arguments
$getposts = get_posts($args);
//Initialize post values
$posta = array();
$postb = array();
//Set the counter to 1
$i=1;
//Loop as long as there are posts.
foreach ($getposts AS $post) {
    //Get an individual post and add it to individual buckets.
    if($i%2 == 1) {
        $posta[] = $post;
    } else {
        $postb[] = $post;
    }
}

现在postapostb分别包含奇数和偶数帖子。你可以在闲暇时循环浏览,并根据自己的喜好发帖。或者,您可以将数据附加到不同的桶中,而不是将它们分配给不同的变量数组。这将帮助您避免第二次或第三次循环。

查看Wordpress Codex模板标签/get帖子了解更多详细信息。