这是一个来自Merging a complex query with post_rewind and splitting posts into two columns
嗨,我的循环需要帮助。is所做的是将帖子分成两列。
<?php $row_start = 1; while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php if( $row_start % 2 != 0) {// odd ?>
<div class="post">
left - <?php the_title();?><br>
</div>
<?php } ;?>
<?php if( $row_start % 2 == 0) {// even ?>
<div class="post">
right - <?php the_title();?><br>
</div>
<?php } ;?>
<?php ++$row_start; endwhile; wp_reset_postdata(); endif; ?>
其输出回路如下:
<div class="left">post</div>
<div class="left">post</div>
<div class="right">post</div>
<div class="left">post</div>
<div class="right">post</div>
<div class="left">post</div>
<div class="right">post</div>
我要做的是将所有帖子包装在一个div中,如下所示:
<div class="left">
post
post
post
</div>
<div class="right">
post
post
post
</div>
谢谢
最合适的回答,由SO网友:gloria 整理而成
您始终可以尝试创建两个标题数组,例如$left和$right、$odd和$even或$tom和$jerry,并在循环过程中用标题填充它们,然后在循环结束后打印它们,如下所示:
创建阵列
$left = $right = array();
然后释放你的循环[编辑以下内容以反映评论]
<?php // The loop
if ( $query->have_posts() ) : $row_start = 1;
while ( $query->have_posts() ) : $query->the_post();
if ( in_array( get_the_ID(), $duplicates ) ) continue;
if( $row_start % 2 != 0) {
// odd: add result to $left
// $left[] = get_the_title();
$left[] = $post->id;
} else {
// even: add it to $right
//$right[] = get_the_title();
$right[] = $post->id;
}
++$row_start; endwhile; wp_reset_postdata();
// now loop has ended and we have 2 full arrays
// that we can print each in it\'s div
print "<div class=\\"left\\">";
foreach($left as $postID) {
$postData = get_post( $postID );
print $postData->post_title;
print $postData->post_content;
// etc... you can also get thumbnails using the post ID:
print get_the_post_thumbnail($postID, \'thumbnail\');
}
print "</div>";
// next column
print "<div class=\\"right\\">";
foreach($right as $postID) {
// ... just like the above...
}
print "</div>";
endif;
?>
我还没有测试过这个,但它应该可以工作(或者是它的一些近似变体)。我个人会在无序列表中输出帖子列表(
<ul class="right or left">
) 并将每个标题放在
<li>
.
祝你好运:)