I want to create a single array of posts by merging the results of 2 separate get_posts
queries, and have the array ordered by published date.
In my code bel
Merging the results of 2 separate queries won't change the order, so you will need to do a sort on them yourself.
Because because get_posts
returns an array of objects, we need to use a sort function that lets you create a user-defined comparison (e.g. usort) - in other words we tell it what values to sort on and in what order.
If you are using PHP 7, you can use an anonymous function for the sort and the "spaceship operator" <=> to do the comparison, so this is all you need:
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;
});
(Note that normally you would use return $a->value <=> $b->value;
to return the results in ascending order, but as we are working with dates and want the newest first, then we need to reverse the comparison to be return $b->value <=> $a->value;
)
So in your code, you just need to use it like this:
<?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: If you are still using PHP 5 (which you shouldn't be!), you can use the following instead:
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;
});