Using meta_query and tax_query at the same time

I’ve got the following displaying correctly on my page template:

<?php
$args = array(
‘post_type’ => ‘givingback’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => 100,
‘meta_query’ => array(
‘relation’ => ‘AND’,
array(
‘key’ => ‘givingback_details_funds’,
‘compare’ => ‘EXISTS’,
),
array(
‘key’ => ‘givingback_details_days’,
‘compare’ => ‘EXISTS’,
)
)
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<!– display if funds and working days found –>
<?php include ‘content-givingback-both.php’;?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<!– display if only funds OR working days found –>
<?php include ‘content-givingback.php’;?>
<?php endif; ?>

But on the taxonomy (category) pages we need to add a taxonomy into the mix so I added:

<?php $page_slug = basename(get_permalink()); ?>
<?php
$args = array(
‘post_type’ => ‘givingback’,
‘posts_per_page’ => 100,
‘gbdealership_category’ => $page_slug,

Posts are filtered by taxonomy, but they all use content-givingback.php (instead of using content-givingback-both.php when both fields have values).

If the taxonomy is empty, instead of showing an empty page all the posts show.

Annoyingly, if the taxonomy is empty, the posts that incorrectly appear on the page use the correct template (content-givingback.php or content-givingback-both.php)

Adding the following to $args filters posts correctly (even when taxonomy is empty), but posts still always use content-givingback.php:

‘tax_query’ => array(
‘relation’ => ‘AND’,
array(
‘taxonomy’ => ‘month_category’,
‘field’ => ‘slug’,
‘terms’ => $page_slug,
),
),

I struggle with PHP so I’m sure it’s something obvious I’m doing wrong.

Read more here:: Using meta_query and tax_query at the same time

Leave a Reply

Your email address will not be published. Required fields are marked *