1

I have a multisite (test) installation of WordPress and want to get the posts of every blog.

After hours, I got the solution for that. But now, I have the merged query and like to sort the posts from each blog by date. Now I get the blog1-posts and after all blog1-posts, I get the blog2-posts.

How to sort the array? Here is the code so far:

$custom_posts = array();

$blog_ids = wp_get_sites();

foreach ($blog_ids as $key=>$current_blog) {

    switch_to_blog($current_blog['blog_id']);

    $query = get_posts("posts_per_page=10");

    $custom_posts = array_merge($custom_posts, $query);

    restore_current_blog();

}

//SORT THE $custom_posts BY POST_DATE? HOW? :(

global $post; 

foreach($custom_posts as $post) : setup_postdata($post);

<<< theposts >>>.
.
endforeach;

I hope this is possible to do.

Or is there any better way to reach the goal?

1

You can try the new (4.7+) wp_list_sort() utility function that's a wrapper for WP_List_Util::sort() that uses usort() or uasort().

Example 1:

Sort by descending post date

$sorted_custom_posts = wp_list_sort( 
    $custom_posts, 
    'post_date', 
    'DESC' 
);

Example 2:

Sort by descending post date and ascending post title

$sorted_custom_posts = wp_list_sort( 
    $custom_posts, 
    [
        'post_date'  => 'DESC',
        'post_title' => 'ASC',
    ]
);

Check the Make post here for more information.

2
  • Wow, thank you very much! That's so easy if you know that :D Before you posted the answer, I found this solution, but your's is my favorite! Thank you very very much! usort($custom_posts, function($a, $b) { return strcmp($b->post_date_gmt, $a->post_date_gmt); });
    – Markus
    May 5 '17 at 8:37
  • You're welcome, glad to hear it helped. @Markus
    – birgire
    May 5 '17 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.