我在存档页上遇到了一个特殊的问题。这个特定页面应该列出属于某个类别的所有帖子,但可以通过第二个(自定义)分类法进行过滤:即:同时属于“新闻”和“娱乐”的帖子(后者属于“主题”分类法)。
问题是,如果没有属于这两个分类术语的帖子,则不应该出现过滤器链接,但到目前为止,我还无法删除“空”链接,因为查询被主链接覆盖——下面是一些代码来解释:
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;
如果我在没有过滤器的情况下运行此程序(例如:example.com/category/news),它会按预期工作,空的过滤器链接不会出现。但是,一旦单击其中一个链接(结果是example.com/category/news/?topic=entertainment),我将再次获得所有筛选链接,“print\\r($topic\\u query,true)”将返回主查询变量和tax\\u查询,而不是次查询。
我为冗长的解释道歉,但我已经做了一段时间了,现在什么也没想到。有什么想法吗?