class MyClass {
...
function post_count_filter($where) {
global $wpdb;
str_replace("WHERE", "WHERE ".$wpdb->posts.".post_parent = ".$this->count_parent." AND", $where);
return $where;
}
function count_children($post_id) {
$this->count_parent = $post_id;
add_filter(\'query\', ( &$this, \'post_count_filter\') );
$stats = wp_count_posts(\'myposttype\');
remove_filter(\'query\', ( &$this, \'post_count_filter\') );
unset($this->count_parent);
return array_sum( (array)$stats );
}
// example of use
function xyz() {
global $post;
...
$child_count = $this->count_children($post->ID);
...
}
...
}
唯一的问题是,wp\\u count\\u posts()会缓存其结果,而且由于您的过滤器会绕过缓存,因此您可能必须首先对缓存进行解密。
或者(更好的做法是)复制wp\\u count\\u posts()函数并根据您的需要进行修改,这样您就不必使用过滤器,也不必对结果进行汇总,也不必像它那样完成其余的操作。