I'm running into a particular problem with an archive page. This particular page is supposed to list all post that belong to a category, but is able to be filtered by a second (custom) taxonomy: i.e.: posts that belong to both 'News' and 'Entertainment' (where the latter belongs to 'Topic' taxonomy).
The problem is that the filter link should not appear if there are no posts that belong to both taxonomy terms, but so far I haven't been able to remove the "empty" links as the query is being overriden by the main one -- here's some code to explain:
if ( is_single() ) {
$cats = get_the_category();
$cat = $cats[0];
} else {
$cat = get_category( get_query_var( 'cat' ) );
}
$topics = get_terms( array(
'taxonomy' => 'topic',
'hide_empty' => true, // thought this would do the trick, but no.
) );
$topic_query_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'nopaging' => true,
);
foreach( $topics as $topic ):
// This could get really slow. Refactor when able.
$topic_tax_query = array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $cat->slug
),
array(
'taxonomy' => 'topic',
'field' => 'slug',
'terms' => $topic->slug
)
);
// Reassign the tax_query for the new $topic->slug:
$topic_query_args['tax_query'] = $topic_tax_query;
// Run secondary query:
$topic_query = new WP_Query( $topic_query_args );
$found_posts = $topic_query->found_posts;
echo '<!--'. print_r( $topic_query, true ) .'-->'.PHP_EOL;
// wp_reset_postdata(); // Probably not needed, as I'm not running $topic_query->the_post()
// Here's the problem -- secondary query returns the same number of posts for all secondary terms:
echo '<!--Found posts for '. $topic->slug .': '. $found_posts .'-->'. PHP_EOL;
if ( $topic_query->found_posts == 0 ) {
// Skip printing the link:
continue;
} else {
// Process and print the link here.
// ...extra code goes here...
}
endforeach;
If I run this with no filters (i.e.: example.com/category/news), it works as expected, the empty filter links do not appear. However, once I click on one of the links (resulting in example.com/category/news/?topic=entertainment) I get all of the filter links again, and the "print_r( $topic_query, true )" returns the main query_vars and tax_query instead of the secondary query's.
I apologize for the long-winded explanation, but I've been at this for a while now and am coming up with nothing. Any ideas?