是否可以查询多个CPT,然后以预设方式订购?
例如,我有2个CPT和1个是WP默认的“ post”,并且希望循环返回6个结果,顺序如下。
是否可以不中断循环?
我确实进行了快速搜索,但是只能找到一篇与此相关的文章,从中看来解决方案似乎不再起作用...
答案 0 :(得分:2)
以下是Sephsekla代码的简化版本:
$my_post_types = array( 'CPT-1', 'CPT-2', 'post', 'CPT-1', 'CPT-2', 'post' );
$posts_shown = array();
$args = array(
'post_type' => array( 'CPT-1', 'CPT-2', 'post' ),
'post_status' => 'publish',
'posts_per_page' => -1
);
$my_query = new WP_Query( $args );
foreach ( $my_post_types as $post_type ):
while ( $my_query->have_posts() ): $my_query->the_post();
if ( $post_type == get_post_type() && ! in_array( get_the_ID(), $posts_shown ) ) {
echo '<pre>' . get_post_type() .': '. get_the_title() . '</pre>';
$posts_shown[] = get_the_id();
break;
}
endwhile;
$my_query->rewind_posts();
endforeach;
wp_reset_postdata();
答案 1 :(得分:1)
这是我前一段时间做过的事情,虽然只需要一个查询就可以完成,但是设置有点麻烦。
其要点是,您可以使用一个查询,然后循环查询直到找到所需的第一篇文章。然后退出循环,并使用WP_Query->rewind_posts()
将查询重新开始。
然后,您可以运行具有不同条件的第二个循环。然后是三分之一。
对于第四,第五和第六个循环,您还需要检查您是否没有重复第一个循环。
请参阅下面的全部代码。
<?php
$my_query = new WP_Query(
array(
'post_status' => 'publish',
)
);
$post_1 = $post_2 = $post_3 = $post_4 = $post_5 = $post_6 = 0;
if ( $my_query->have_posts() ) {
/*First loop through posts*/
while ( $my_query->have_posts() ) {
$my_query->the_post();
/**
* Find the first post
*/
if ( 'CPT-1' == get_post_type() && $post_1 == 0 ) {
do_something_with_the_post();
$post_1 = get_the_id();
break;
}
}
$my_query->rewind_posts();
/*Second loop through posts*/
while ( $my_query->have_posts() ) {
$my_query->the_post();
/**
* Find the second post
*/
if ( 'CPT-2' == get_post_type() && $post_2 == 0 ) {
do_something_with_the_post();
$post_2 = get_the_id();
break;
}
}
$my_query->rewind_posts();
/*Third loop through posts*/
while ( $my_query->have_posts() ) {
$my_query->the_post();
/**
* Find the third post
*/
if ( 'post' == get_post_type() && $post_3 == 0 ) {
do_something_with_the_post();
$post_3 = get_the_id();
break;
}
}
$my_query->rewind_posts();
/**
* Then we repeat this process but also check we don't use the same post twice
*/
/*Fourth loop through posts*/
while ( $my_query->have_posts() ) {
$my_query->the_post();
/**
* Find the fourth post
*/
if ( 'CPT-1' == get_post_type() && $post_4 == 0 && get_the_id() !== $post_1 ) {
do_something_with_the_post();
$post_1 = get_the_id();
break;
}
}
$my_query->rewind_posts();
/*Fifth loop through posts*/
while ( $my_query->have_posts() ) {
$my_query->the_post();
/**
* Find the fifth post
*/
if ( 'CPT-2' == get_post_type() && $post_5 == 0 && get_the_id() !== $post_2 ) {
do_something_with_the_post();
$post_5 = get_the_id();
break;
}
}
$my_query->rewind_posts();
/*Sixth loop through posts*/
while ( $my_query->have_posts() ) {
$my_query->the_post();
/**
* Find the sixth post
*/
if ( 'post' == get_post_type() && $post_6 == 0 && get_the_id() !== $post_3 ) {
do_something_with_the_post();
$post_6 = get_the_id();
break;
}
}
/**
* And we're finished
*/
}