wp_count_comments() WordPress Function

The wp_count_comments() function is used to retrieve the number of comments that have been made on a given post. This function will return an integer value representing the number of comments that have been made on the specified post.

wp_count_comments( int $post_id ) #

Retrieves the total comment counts for the whole site or a single post.


Description

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

Top ↑

See also


Top ↑

Parameters

$post_id

(int)(Optional) Restrict the comment counts to the given post. Default 0, which indicates that comment counts for the whole site will be retrieved.


Top ↑

Return

(stdClass) The number of comments keyed by their status.

  • 'approved'
    (int) The number of approved comments.
  • 'moderated'
    (int) The number of comments awaiting moderation (a.k.a. pending).
  • 'spam'
    (int) The number of spam comments.
  • 'trash'
    (int) The number of trashed comments.
  • 'post-trashed'
    (int) The number of comments for posts that are in the trash.
  • 'total_comments'
    (int) The total number of non-trashed comments, including spam.
  • 'all'
    (int) The total number of pending or approved comments.


Top ↑

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 or the whole site.
	 *
	 * @since 2.7.0
	 *
	 * @param array|stdClass $count   An empty array or an object containing comment counts.
	 * @param int            $post_id The post ID. Can be 0 to represent the whole site.
	 */
	$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
VersionDescription
2.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More