Skip to content

Instantly share code, notes, and snippets.

@waqasy
Forked from jcobb/gist:2993853
Created September 1, 2017 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waqasy/3be6fe13e9cfe6966959e72eed7825a6 to your computer and use it in GitHub Desktop.
Save waqasy/3be6fe13e9cfe6966959e72eed7825a6 to your computer and use it in GitHub Desktop.
Combine multiple WordPress queries
<?php
// An example of creating two separate WP queries, combining the results,
// sorting by date and formatting the results for us in a loop like a regular query.
// order the posts by date in descending order (should go in functions.php to keep things tidy)
function order_by_date( $a, $b )
{
return strcmp( $b->post_date, $a->post_date );
}
// get the posts for the first query
$q1_args = array(
// args for the first query
);
$q1_posts = get_posts( $q1_args );
// get the posts for the second query
$q2_args = array(
// args for the second query
);
$q2_posts= get_posts( $q2_args );
// Merge the post arrays together, and sort by date using the order_by_date function
$final_posts = array_merge( $q1_posts, $q2_posts );
usort( $final_posts, 'order_by_date' );
// Loop over the posts and use setup_postdata to format for template tag usage
foreach ( $final_posts as $key => $post ) {
setup_postdata( $post );
// Now we can use template tags as if this was in a normal WP loop
the_title('<h2>','</h2>');
the_content();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment