合并两个单独查询的结果不会改变顺序,因此您需要自己对它们进行排序。
因为因为get_posts
返回一个对象数组,我们需要使用一个排序函数来创建用户定义的比较(例如usort https://www.php.net/manual/en/function.usort.php) - 换句话说,我们告诉它要根据哪些值以及以什么顺序进行排序。
如果您正在使用PHP 7,您可以使用匿名函数进行排序和“宇宙飞船操作员”<=> https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php/31298778#31298778进行比较,所以这就是您所需要的:
usort($my_posts, function($post_a, $post_b) {
// Compare the post_date of the posts, and if $post_b is newer, then it will be displayed first
return $post_b->post_date <=> $post_a->post_date;
});
(请注意,通常您会使用return $a->value <=> $b->value;
以升序返回结果,但由于我们正在处理日期并希望最新的第一个,那么我们需要将比较反转为return $b->value <=> $a->value;
)
所以在你的代码中,你只需要像这样使用它:
<?php
// do your merge...
$my_posts= array_merge( get_posts($args_b), get_posts($args_a) );
// sort the resulting array...
usort($my_posts, function($post_a, $post_b) {
return $post_b->post_date <=> $post_a->post_date;
});
// and now process the new sorted array as required.
foreach($my_posts as $post):setup_postdata($post);?>
<?php the_title(); ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
UPDATE: 如果您还在使用PHP 5(你不应该这样做!),你可以使用以下内容代替:
usort($my_posts, function ($a, $b) {
if ($a->post_date < $b->post_date) return -1;
elseif ($a->post_date > $b->post_date) return 1;
else return 0;
});