我认为这里最好的方法是在这里运行三个单独的循环(你也可以做两个循环,但是你需要在男性和女性查询中获得完整的帖子,将它们合并并重新排列),前两个循环将用于获得5个男性,第二个循环将获得2个女性。您可以根据需要对此进行调整。第三个循环将使用前两个循环中的信息来获取完整的帖子。
在这里,我接受您使用的自定义字段有两个单独的值,一个用于男性,一个用于女性。此外,我接受您不需要为这个查询分页。
你可以试试这样的
/*
* First query to get 5 men. Only get post ID\'s to increase performance
*/
$args1 = array(
\'posts_per_page\' => 5,
\'orderby\' => \'rand\',
\'suppress_filters\' => true,
\'no_found_rows\' => true,
\'fields\' => \'ids\',
\'meta_query\' => array(
array(
\'key\' => \'custom-field-name\',
\'value\' => \'value-for-men\',
)
)
);
$men = new WP_Query( $args1 );
/*
* Second query to get 2 women. Only get post ID\'s to increase performance
*/
$args2 = array(
\'posts_per_page\' => 2,
\'orderby\' => \'rand\',
\'suppress_filters\' => true,
\'no_found_rows\' => true,
\'fields\' => \'ids\',
\'meta_query\' => array(
array(
\'key\' => \'custom-field-name\',
\'value\' => \'value-for-women\',
)
)
);
$women = new WP_Query( $args2 );
/*
* Merge the post id\'s from the two queries
*/
$merged_ids = array_merge( $women->posts, $men->posts );
/*
* Use the merged array of post id\'s to get the complete posts. Use \'orderby\' => \'post__in\'
* to keep shuffled order of the posts that will be returned
*/
$args3 = array(
\'post__in\' => shuffle( $merged_ids ),
\'orderby\' => \'post__in\'
);
$merged_queries = new WP_Query( $args3 );
?><pre><?php var_dump($merged_queries->posts); ?></pre><?php