Get the post children count of a post

Is there a fast way to get the count (number) of post children of a certain post?
(The post has a custom post type)

I don’t want to use WP_Query for this because I don’t need all the extra data…

Read More

LE: based on wyrfel’s answer I ended up using:

function reply_count($topic, $type = 'topic-reply'){
  global $wpdb;
  $cache_key = "{$type}_{$topic}_counts";
  $count = wp_cache_get($cache_key, 'counts');
  if(false !== $count) return $count;
  $query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_parent = %d AND post_type = %s";
  $count = $wpdb->get_var($wpdb->prepare($query, $topic, $type));
  wp_cache_set($cache_key, $count, 'counts');
  return $count;
}

Related posts

Leave a Reply

1 comment

  1. 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);
            ...
        }
    
        ...
    
    }
    

    The only issue with that is that wp_count_posts() caches its results and since your filter bypasses the cache you might have to devalidate the cache, first.

    Or (better), copy the wp_count_posts() function and modify it to your needs, so you don’t have to use the filter, don’t have to sum up the results and avoid having the rest done that it does.