get_comment_count

The amount of comments in a post or total comments.

Description

(array) get_comment_count( (int) $post_id = 0 ); 

A lot like wp_count_comments(), in that they both return comment stats (albeit with different types). The wp_count_comments() actually caches, but this function does not.

Returns (array)

The amount of spam, approved, awaiting moderation, and total comments.

Parameters (1)

0. $post_id — Optional. (int)
Comment amount in post if > 0, else total comments blog wide.

Usage

  1. if ( !function_exists( 'get_comment_count' ) ) { 
  2. require_once ABSPATH . WPINC . '/comment.php'; 
  3.  
  4. // Optional. Comment amount in post if > 0, else total comments blog wide. 
  5. $post_id = -1; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = get_comment_count($post_id); 
  9.  

Defined (1)

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

/wp-includes/comment.php  
  1. function get_comment_count( $post_id = 0 ) { 
  2. global $wpdb; 
  3.  
  4. $post_id = (int) $post_id; 
  5.  
  6. $where = ''; 
  7. if ( $post_id > 0 ) { 
  8. $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id); 
  9.  
  10. $totals = (array) $wpdb->get_results(" 
  11. SELECT comment_approved, COUNT( * ) AS total 
  12. FROM {$wpdb->comments} 
  13. {$where} 
  14. GROUP BY comment_approved 
  15. ", ARRAY_A); 
  16.  
  17. $comment_count = array( 
  18. 'approved' => 0,  
  19. 'awaiting_moderation' => 0,  
  20. 'spam' => 0,  
  21. 'trash' => 0,  
  22. 'post-trashed' => 0,  
  23. 'total_comments' => 0,  
  24. 'all' => 0,  
  25. ); 
  26.  
  27. foreach ( $totals as $row ) { 
  28. switch ( $row['comment_approved'] ) { 
  29. case 'trash': 
  30. $comment_count['trash'] = $row['total']; 
  31. break; 
  32. case 'post-trashed': 
  33. $comment_count['post-trashed'] = $row['total']; 
  34. break; 
  35. case 'spam': 
  36. $comment_count['spam'] = $row['total']; 
  37. $comment_count['total_comments'] += $row['total']; 
  38. break; 
  39. case '1': 
  40. $comment_count['approved'] = $row['total']; 
  41. $comment_count['total_comments'] += $row['total']; 
  42. $comment_count['all'] += $row['total']; 
  43. break; 
  44. case '0': 
  45. $comment_count['awaiting_moderation'] = $row['total']; 
  46. $comment_count['total_comments'] += $row['total']; 
  47. $comment_count['all'] += $row['total']; 
  48. break; 
  49. default: 
  50. break; 
  51.  
  52. return $comment_count;