一个更快的解决方案是查询数据库一次,而不是对每个post ex反复查询:
function count_posts_in_term($posts = array(),$term_taxonomy_id = 0){
global $wpdb;
$count = 0 ;
$count = $wpdb->get_var(
$wpdb->prepare("SELECT count(object_id)
FROM $wpdb->term_relationships
WHERE term_taxonomy_id = %s
AND object_id IN(".implode(\',\',$posts).")",
$term_taxonomy_id
)
);
return $count;
}
用法:
echo count_posts_in_term($array_of_posts,$cat_term_id);