Last active
June 20, 2017 11:45
-
-
Save alexstandiford/baff67f18f18e11f5613ede821dd3dee to your computer and use it in GitHub Desktop.
Combine two WordPress Queries and append the results to the final query
This file contains 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 | |
/** | |
* 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; | |
} | |
} | |
} |
This file contains 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 | |
//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