Это то, что я делал некоторое время назад, и хотя его можно выполнить всего одним запросом, это немного сложная настройка.
Суть в том, что вы можете использовать один запрос, а затем перебирать запрос, пока не найдете первое сообщение, за которым вы следите. Затем выйдите из цикла и используйте 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
*/
}