I have a custom query that in another iteration I'm using to only display events in the future:
$today = date('Ymd');
if ( is_post_type_archive('event')) {
$eventPosts = new WP_Query(array(
'posts_per_page' => '-1',
'post_type' => 'event',
'meta_key' => 'date_and_time',
'order_by' => ' meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'date_and_time',
'compare' => '>=',
'value' => $today,
'type' => 'numeric'
)
)
));
However this was done using a separate loop in a separate template. I'd like to keep things DRY so is it possible to output this conditionally so that I can use my existing archive.php loop? Something like this:
if (have_posts() : OR $eventPosts->have_posts()) :
while (have_posts()) :
?>
<div class="card container mb-3">
Or otherwise what would be best practice in this case?
Many thanks!
I have a custom query that in another iteration I'm using to only display events in the future:
$today = date('Ymd');
if ( is_post_type_archive('event')) {
$eventPosts = new WP_Query(array(
'posts_per_page' => '-1',
'post_type' => 'event',
'meta_key' => 'date_and_time',
'order_by' => ' meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'date_and_time',
'compare' => '>=',
'value' => $today,
'type' => 'numeric'
)
)
));
However this was done using a separate loop in a separate template. I'd like to keep things DRY so is it possible to output this conditionally so that I can use my existing archive.php loop? Something like this:
if (have_posts() : OR $eventPosts->have_posts()) :
while (have_posts()) :
?>
<div class="card container mb-3">
Or otherwise what would be best practice in this case?
Many thanks!
Found a ready made solution posted in the codex: https://developer.wordpress/reference/hooks/pre_get_posts/
The trick here is the pre_get_posts hook which modifies the query variable 'after the query variable object is created, but before the actual query is run' so that if the post type is an event, it sorts in the same way I'd been doing already. Put this in functions.php
function university_adjust_queries($query){
if ( ! is_admin() && is_post_type_archive( 'event' ) && $query->is_main_query() ) {
$query->set( 'meta_key', 'event_date' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'ASC');
$query->set( 'meta_query', array(
array(
'key' => 'event_date',
'compare' => '>=',
'value' => date('Ymd'),
'type' => 'numeric',
)
) );
}
}
add_action( 'pre_get_posts', 'university_adjust_queries' );
Thanks to saddamcrr7