我有一个$array
打印结果如下。
Array ( [post-12] => 12 [post-160] => 160 )
我试着做了以下事情。
$post_id_array = $array;
$category = \'45\';
$count = count(in_category( $category, $post_id_array ));
echo $count;
它不起作用。我有一个$array
打印结果如下。
Array ( [post-12] => 12 [post-160] => 160 )
我试着做了以下事情。
$post_id_array = $array;
$category = \'45\';
$count = count(in_category( $category, $post_id_array ));
echo $count;
它不起作用。我已使用以下代码成功返回计数。以防万一以后有人会看到这个问题。
$count = 0;
$category = \'45\';
foreach ( $array as $post_id ) {
if (in_category( $category, $post_id )) {
$count++;
}
}
echo $count;
一个更快的解决方案是查询数据库一次,而不是对每个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);
我有以下表格(为了简洁明了,仅包含相关信息)表名称:wp\\U term\\U关系object_id term_taxonomy_id 1266 1341 1266 452 1266 449 表格名称:wp\\U term\\U taxonomyterm_taxonomy_id term_id 1341 1342 452 453