我正在我的首页上建立一个帖子网格,我想每个CPT显示一个随机帖子。目前,CPT是在查询数组中查询出来的:
<?php
$c = 1; //init counter
$bpr = 3; //boxes per row
$wp_query = new WP_Query(array(\'showposts\' => 9, \'orderby\'=> \'rand\', \'post_type\' => array(\'productions\', \'plays\', \'movies\', \'theatres\', \'directors\', \'artists\', \'countries\', \'events\', \'grades\')));
while( have_posts() ) : the_post(); ?>
<div class="post" id="post-<?php the_ID(); ?>">
<p><?php $post_type = get_post_type_object( get_post_type($post) ); echo $post_type->label ; ?></p>
<a href="<?php the_permalink() ?>" rel="bookmark">
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail(\'thumbnail\');
} else { ?>
<img src="<?php bloginfo(\'template_directory\'); ?>/img/fallback_image.jpg" alt="<?php the_title(); ?>" />
<?php } ?>
</a>
</div>
<?php
if($c == $bpr) :
?>
<div class="clr"></div>
<?php
$c = 0;
endif;
?>
<?php
$c++;
endwhile;
?>
所以这个数组的问题是,当我查询CPT时,它开始重复CPT,有时甚至它会查询CPT中的4篇随机帖子。
一种解决方案是创建9个不同的查询—每个CPT一个查询,但这对于首页来说似乎有点过头了。
有没有一种方法可以在不影响页面加载时间的情况下,在每个CPT中只查询1篇随机帖子?
最合适的回答,由SO网友:Chris_O 整理而成
此方法可能适合您。你将不得不获取比你需要的更多的帖子,但这比进行9次查询要好。
$args = array(
\'post_type\' => array( \'type1\', \'type2\', \'type3\', \'etc...\' ),
\'posts_per_page\' => -1
);
$myquery = new WP_Query( $args );
$type1 = 0; $type2 = 0; $type3 = 0; $count = 0;
while ( $myquery->have_posts() ) : $myquery->the_post();
if ( $post->post_type == \'type1\' ) $type1++;
if ( $post->post_type == \'type1\' && $type1 > 1 ) continue;
if ( $post->post_type == \'type2\' ) $type2++;
if ( $post->post_type == \'type2\' && $type2 > 1 ) continue;
if ( $post->post_type == \'type3\' ) $type3++;
if ( $post->post_type == \'type3\' && $type3 > 1 ) continue;
// I stopped at 3 but keep going as far as you need.
$count++; if ( $count > 9 ) continue;
// Do Stuff
endwhile;