wp_count_comments

Retrieve total comments for blog or single post.

Description

(object|array) wp_count_comments( (int) $post_id = 0 ); 

The properties of the returned object contain the moderated,, approved, and spam comments for either the entire blog or single post. Those properties contain the amount of comments that match the status. The total_comments property contains the integer of total comments.

The comment stats are cached and then retrieved, if they already exist in the cache.

Returns (object|array)

Comment stats.

Parameters (1)

0. $post_id — Optional. (int)
Post ID.

Usage

  1. if ( !function_exists( 'wp_count_comments' ) ) { 
  2. require_once ABSPATH . WPINC . '/comment.php'; 
  3.  
  4. // Optional. Post ID. 
  5. $post_id = -1; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wp_count_comments($post_id); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/comment.php  
  1. function wp_count_comments( $post_id = 0 ) { 
  2. $post_id = (int) $post_id; 
  3.  
  4. /** 
  5. * Filters the comments count for a given post. 
  6. * @since 2.7.0 
  7. * @param array $count An empty array. 
  8. * @param int $post_id The post ID. 
  9. */ 
  10. $filtered = apply_filters( 'wp_count_comments', array(), $post_id ); 
  11. if ( ! empty( $filtered ) ) { 
  12. return $filtered; 
  13.  
  14. $count = wp_cache_get( "comments-{$post_id}", 'counts' ); 
  15. if ( false !== $count ) { 
  16. return $count; 
  17.  
  18. $stats = get_comment_count( $post_id ); 
  19. $stats['moderated'] = $stats['awaiting_moderation']; 
  20. unset( $stats['awaiting_moderation'] ); 
  21.  
  22. $stats_object = (object) $stats; 
  23. wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' ); 
  24.  
  25. return $stats_object;