Skip to content

Instantly share code, notes, and snippets.

@alexstandiford
Last active June 20, 2017 11:45
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 alexstandiford/baff67f18f18e11f5613ede821dd3dee to your computer and use it in GitHub Desktop.
Save alexstandiford/baff67f18f18e11f5613ede821dd3dee to your computer and use it in GitHub Desktop.
Combine two WordPress Queries and append the results to the final query
<?php
/**
* Combines two WP_Queries, and appends the second to the first
* @author: Alex Standiford
* @date : 6/20/2017
*/
class mergedQuery extends \WP_Query{
public $post_ids_to_merge = [];
public function __construct($query_args, $primary_args){
parent::__construct();
$this->posts = [];
foreach($query_args as $query_arg){
$query_to_merge = new WP_Query($query_arg);
$this->posts = array_merge($this->posts,$query_to_merge->posts);
$this->post_count += $query_to_merge->post_count;
}
}
}
<?php
//This example creates a query that will display all upcoming events first, and then display past events afterward
$webcasts = new mergedQuery([
//Query 1
[
'post_type' => 'tribe_events',
'posts_per_page' => 5,
'tax_query' => [
'relation' => 'OR', [
'taxonomy' => 'tribe_events_cat',
'field' => 'slug',
'terms' => 'webcasts',
]],
'order' => 'asc',
'orderby' => 'EventStartDate',
'eventDisplay' => 'upcoming',],
//Query 2
[
'post_type' => 'tribe_events',
'posts_per_page' => 5,
'tax_query' => [
'relation' => 'OR', [
'taxonomy' => 'tribe_events_cat',
'field' => 'slug',
'terms' => 'webcasts',
]],
'order' => 'desc',
'orderby' => 'EventStartDate',
'eventDisplay' => 'past',],
],
[
//Additional args for resulting query
'post_type' => 'tribe_events',
'eventDisplay' => 'custom',
'start_date' => date('y-m-d m:i', strtotime('-1 year')),
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment