您可以尝试对数据库中的所有结果执行一次查询,然后使用get_post_type()
将结果分解为每个帖子类型的单独循环。如果PHP操作比使用两个数据库查询更快,那么根据您正在使用的内容,它可能会提高性能,不过您必须自己进行测试。
<?php
$all_results = new WP_Query([
\'post_type\' => [\'post_type_1\', \'post_type_2\']
]);
// initiate counter variables
$count_post_type_1s = 0;
$count_post_type_2s = 0;
while ( $all_results->have_posts() ) : $all_results->the_post();
if( get_post_type($post) == \'post_type_1\' ) {
// increment counter variable for post type 1 being found
$count_post_type_1s++;
// post_type_1 output
the_title();
}
endwhile;
// check if counter variable is still 0, if it is no post type 1\'s were found
if( $count_post_type_1s == 0 ) {
echo "No post type 1\'s have been found";
}
// Rewind posts to use same query again
$all_results->rewind_posts();
// do some stuff in between loops
while ( $all_results->have_posts() ) : $all_results->the_post();
// increment counter variable for post type 2 being found
$count_post_type_2s++;
if( get_post_type($post) == \'post_type_2\' ) {
// post_type_2 output
the_title();
}
endwhile;
// check if counter variable is still 0, if it is no post type 2\'s were found
if( $count_post_type_2s == 0 ) {
echo "No post type 2\'s have been found";
}