wp_count_comments( int $post_id )

Retrieve total comments for blog or single post.


Description Description

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.


Parameters Parameters

$post_id

(int) (Optional) Post ID.


Top ↑

Return Return

(object|array) Comment stats.


Top ↑

Source Source

File: wp-includes/comment.php

function wp_count_comments( $post_id = 0 ) {
	$post_id = (int) $post_id;

	/**
	 * Filters the comments count for a given post.
	 *
	 * @since 2.7.0
	 *
	 * @param array $count   An empty array.
	 * @param int   $post_id The post ID.
	 */
	$filtered = apply_filters( 'wp_count_comments', array(), $post_id );
	if ( ! empty( $filtered ) ) {
		return $filtered;
	}

	$count = wp_cache_get( "comments-{$post_id}", 'counts' );
	if ( false !== $count ) {
		return $count;
	}

	$stats              = get_comment_count( $post_id );
	$stats['moderated'] = $stats['awaiting_moderation'];
	unset( $stats['awaiting_moderation'] );

	$stats_object = (object) $stats;
	wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' );

	return $stats_object;
}

Top ↑

Changelog Changelog

Changelog
Version Description
2.5.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Codex

    Retrieve comment count for a post

    <?php
    $comments_count = wp_count_comments( 2492 );
    echo "Comments for post 2492 <br />";
    echo "Comments in moderation: " . $comments_count->moderated . "<br />"; 
    echo "Comments approved: " . $comments_count->approved . "<br />";
    echo "Comments in Spam: " . $comments_count->spam . "<br />";
    echo "Comments in Trash: " . $comments_count->trash . "<br />";
    echo "Total Comments: " . $comments_count->total_comments . "<br />";
    ?>
    
    
  2. Skip to note 2 content
    Contributed by Codex

    Default usage
    Retrieve comment count for a site.

    <?php
    $comments_count = wp_count_comments();
    echo "Comments for site <br />";
    echo "Comments in moderation: " . $comments_count->moderated . "<br />"; 
    echo "Comments approved: " . $comments_count->approved . "<br />";
    echo "Comments in Spam: " . $comments_count->spam . "<br />";
    echo "Comments in Trash: " . $comments_count->trash . "<br />";
    echo "Total Comments: " . $comments_count->total_comments . "<br />";
    ?>
    
    

You must log in before being able to contribute a note or feedback.