Uses
Uses | Description |
---|---|
wp-includes/wp-db.php: wpdb::get_results() | Retrieves an entire SQL result set from the database (i.e., many rows). |
wp-includes/wp-db.php: wpdb::prepare() | Prepares a SQL query for safe execution. |
Retrieves the total comment counts for the whole site or a single post.
Unlike wp_count_comments(), this function always returns the live comment counts without caching.
(int) (Optional) Restrict the comment counts to the given post. Default 0, which indicates that comment counts for the whole site will be retrieved.
(array()) The number of comments keyed by their status.
File: wp-includes/comment.php
function get_comment_count( $post_id = 0 ) { global $wpdb; $post_id = (int) $post_id; $where = ''; if ( $post_id > 0 ) { $where = $wpdb->prepare( 'WHERE comment_post_ID = %d', $post_id ); } $totals = (array) $wpdb->get_results( " SELECT comment_approved, COUNT( * ) AS total FROM {$wpdb->comments} {$where} GROUP BY comment_approved ", ARRAY_A ); $comment_count = array( 'approved' => 0, 'awaiting_moderation' => 0, 'spam' => 0, 'trash' => 0, 'post-trashed' => 0, 'total_comments' => 0, 'all' => 0, ); foreach ( $totals as $row ) { switch ( $row['comment_approved'] ) { case 'trash': $comment_count['trash'] = $row['total']; break; case 'post-trashed': $comment_count['post-trashed'] = $row['total']; break; case 'spam': $comment_count['spam'] = $row['total']; $comment_count['total_comments'] += $row['total']; break; case '1': $comment_count['approved'] = $row['total']; $comment_count['total_comments'] += $row['total']; $comment_count['all'] += $row['total']; break; case '0': $comment_count['awaiting_moderation'] = $row['total']; $comment_count['total_comments'] += $row['total']; $comment_count['all'] += $row['total']; break; default: break; } } return array_map( 'intval', $comment_count ); }
Version | Description |
---|---|
2.0.0 | Introduced. |
© 2003–2019 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/functions/get_comment_count