I have call-to-action posts that I want to display on my front page. I'd like to query these custom post types and display one of them that has a launch date < today's date, and an expiry date > today's date. If there aren't any that meet these conditions, I want to display a call-to-action that doesn't have an expiry date.
Is there a way I can query all call-to-action posts, then randomly display one that meets the first condition, and then if empty, the second condition?
I've successfully tried querying twice, one for each condition (see below). But I think I'd rather query the database once. As this way I can add further conditions as needed, without making innumerable queries. Or would this approach be ill-advised?
$today = date( "Ymd" );
// args
$condition1 = array(
'posts_per_page' => 1,
'post_type' => 'cta',
'post-status' => 'publish',
'orderby' => 'rand',
'meta_query' =>array(
'relation' => 'AND',
array(
'key' => 'launch',
'value' => $today,
'compare' => '<'
),
array(
'key' => 'expiry',
'value' => $today,
'compare' => '>'
),
)
);
$condition2 = array(
'posts_per_page' => 1,
'post_type' => 'cta',
'post-status' => 'publish',
'orderby' => 'rand',
'meta_query' =>array(
array(
'key' => 'launch',
'value' => $today,
'compare' => '<'
),
)
);
// query
$cta1 = new WP_Query( $condition1 );
$cta2 = new WP_Query( $condition2 );
if( !empty($cta1 -> have_posts()) ) :
while( $cta1 -> have_posts() ) : $cta1 -> the_post(); global $post;
// Display post with first condition
endwhile; wp_reset_postdata();
elseif( ( $cta2 -> have_posts() ) ) :
while( $cta2 -> have_posts() ) : $cta2 -> the_post(); global $post;
// Display post with second condition
endwhile; wp_reset_postdata();
endif;