Last active
December 13, 2021 20:38
-
-
Save amouratoglou/05eb4366a45dad4b405a4fc3d232f703 to your computer and use it in GitHub Desktop.
Wordpress PHP Combine two wp queries of different post types - merge 2 arrays and sort by date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// first query | |
$first_ids = get_posts( array( | |
'post_status'=> 'publish', | |
'orderby' => 'date', | |
'post_type'=> 'press', | |
'posts_per_page' => -1, | |
'order' => 'DESC', | |
)); | |
// second query | |
$second_ids = get_posts( array( | |
'orderby' => 'date', | |
'post_type'=> 'post', | |
'category_name'=>'highlights', | |
'posts_per_page' => -1, | |
'order' => 'DESC', | |
)); | |
// merging arrays using array_merge() | |
$posts = array_merge( $first_ids, $second_ids); | |
// sorting with usort() | |
usort($posts, function($post_a, $post_b) { | |
return $post_b->post_date <=> $post_a->post_date; | |
}); | |
// loop them with a for each | |
foreach($posts as $post){ | |
// here ad your magic | |
the_title(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment