假设我想显示30个帖子:10个类型为"A", 10个类型为"B", 10个类型为"C"。按发布日期排序。
我该怎么做?
我的意思是我可以做
$args = array(
'posts_per_page' => 30,
'post_type' => array("A", "B", "C"),
);
$posts = get_posts( $args );
但是它只会给我带来30篇最新的文章,而不是10篇。
您可以创建一个函数并传入您想要的类型和每种类型的数量,然后对它们运行WP_Query,并返回您的帖子。
。
function so_getEqualPosts($number_posts, $post_types){
$postsToReturn = array();
foreach ($post_types as $post_type) {
$args = array(
'post_type' => $post_type,
'posts_per_page' => $number_posts,
'orderby' => 'date',
'order' => 'DESC'
);
$result = new WP_Query($args);
array_push($postToReturn, $result->posts);
}
usort($postsToReturn, function($a, $b) {
return strtotime($a['post_date']) - strtotime($b['post_date']);
});
return $postsToReturn;
}
**以上更新以符合OP要求**另一个选择是使用StdClass;
$postsToReturn = new StdClass();
然后在每次迭代中添加:
$postsToReturn->$post_type = $result->posts;
然后你可以用:
$posts = so_getEqualPosts(30, ["A", "B", "C"]);
文章应该可以通过以下方式访问:
$posts->A
$posts->B
$posts->C
等。
这是未经测试的,非常匆忙,但应该给你一个起点:)