您可以尝试使用terms_clauses
滤器
function wpse156370_terms_clauses( $pieces, $taxonomies, $args ) {
global $wpdb;
$pieces[\'fields\'] .= $wpdb->prepare( \', (SELECT COUNT(*) FROM \'
. $wpdb->posts . \' p, \' . $wpdb->term_relationships . \' p_tr\'
. \' WHERE p_tr.object_id = p.ID AND p_tr.term_taxonomy_id = tt.term_taxonomy_id\'
. \' AND p.post_status = %s AND p.post_type = %s) AS post_count\', \'publish\', $args[\'type\'] );
$pieces[\'orderby\'] = \' HAVING post_count > 0 \' . $pieces[\'orderby\'];
return $pieces;
}
然后在
get_categories
add_filter( \'terms_clauses\', \'wpse156370_terms_clauses\', 10, 3 );
$categories = get_categories( $args );
remove_filter( \'terms_clauses\', \'wpse156370_terms_clauses\', 10, 3 );
这是一种黑客行为,滥用拥有(和
$pieces[\'orderby\']
) as不能引用WHERE中的post\\u count别名,但。。。似乎有效。
要获取要区分的术语链接,请为每个术语添加一个查询变量,例如
echo "<a href=\'" . add_query_arg( \'post_type\', $post_type, get_term_link($cat) ) . "\'>" , $cat->name , "</a>";
然后在
pre_get_posts
行动
function wpse156370_pre_get_posts($query) {
$taxonomy = \'art_categories\';
$post_types = array( \'artists\', \'educations\' );
if ($query->is_main_query() && $query->is_tax( $taxonomy ) && ( $post_type = get_query_var( \'post_type\' ) ) && in_array( $post_type, $post_types ) ) {
$query->set( \'post_type\', $post_type );
}
}
add_action( \'pre_get_posts\', \'wpse156370_pre_get_posts\' );