我希望有2列标题跟随2行内容,然后重复直到查询完成。
示例:
<div><?php the_title(); ?></div>
<div><?php the_title(); ?></div>
<div><?php the_content(); ?></div>
<div><?php the_content(); ?></div>
<div><?php the_title(); ?></div>
<div><?php the_title(); ?></div>
<div><?php the_content(); ?></div>
<div><?php the_content(); ?></div>
这是我目前的代码
<?php
$teams = new WP_Query(array(
'post_type' => 'team-post'
)
);
if ($teams->have_posts()) : while ($teams->have_posts()) : $teams->the_post();?>
<?php if( $teams->current_post%2 == 0 ) echo "\n".'<div class="row">'."\n"; ?>
<div class="col-md-6"><?php the_title(); ?></div>
<?php if( $teams->current_post%2 == 1 || $teams->current_post == $teams->post_count-1 ) echo '</div> <!--/.row-->'."\n"; ?>
<div class="col-md-12"><?php the_content(); ?></div>
<?php endwhile; endif; wp_reset_query();?>
查询的问题在于它遍历每个条目并首先输出TITLE然后输出CONTENT,这是常态。我希望能够首先获得2个TITLES,然后再输入2个条目的内容,然后重复。
答案 0 :(得分:0)
通过这种方式循环播放你无法做你想做的事情。您需要编写for
循环并使用递增数字一次获得两个帖子。
如果是我,我会看看HTML / CSS结构,看看是否有更好的方法来实现所需的效果,但如果你已经设置了这样的PHP解决方案,那么这样就可以了:
$teams = new WP_Query( array( 'post_type' => 'team-post' ) );
$total_posts = count( $teams->posts );
for ( $i = 0; $i < $total_posts; $i += 2 ) {
$left_post = $teams->posts[ $i ];
$right_post = ( isset( $teams->posts[ $i + 1 ] ) ) ? $teams->posts[ $i + 1 ] : false;
?>
<div class="row">
<div class="col-md-6"><?php echo get_the_title( $left_post->ID ); ?></div>
<?php if ( $right_post ) { ?>
<div class="col-md-6"><?php echo get_the_title( $right_post->ID ); ?></div>
<?php } ?>
<div class="col-md-12"><?php echo apply_filters( 'the_content', $left_post->post_content ); ?></div>
<?php if ( $right_post ) { ?>
<div class="col-md-12"><?php echo apply_filters( 'the_content', $right_post->post_content ); ?></div>
<?php } ?>
</div>
<?php
}
这也考虑了奇数帖子的可能性。