没关系。我在这个解决方案中看到的唯一问题是,选择所有帖子数据只是为了检查此类帖子是否存在(帖子可能很长)。
因此,在这种情况下,我会考虑使用自定义查询(它会给您分配此术语的帖子数量)
function my_count_posts_with_term($taxonomy, $term_slug, $post_type) {
$term = get_term_by( \'slug\', $term_slug, $taxonomy );
$count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM {$wpdb->posts}
INNER JOIN {$wpdb->term_relationships}
ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)
INNER JOIN {$wpdb->term_taxonomy}
ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id)
WHERE {$wpdb->posts}.post_type = %s
AND {$wpdb->term_taxonomy}.taxonomy = %s
AND {$wpdb->term_taxonomy}.term_id = %d;", $post_type, $taxonomy, $term->term_id));
return $count;
}