get_comments()WP 2.7.0

Gets comments based on specified parameters, in the form of an array of data.

No Hooks.

Returns

WP_Comment[]|Int[]|Int. Array of comment objects:

Array (
	[0] => stdClass Object
		(
			[comment_ID] => 7999
			[comment_post_ID] => 4896
			[comment_author] => Kama
			[comment_author_email] => [email protected]
			[comment_author_url] =>
			[comment_author_IP] => 65.229.196.81
			[comment_date] => 2014-09-08 13:16:09
			[comment_date_gmt] => 2014-09-08 09:16:09
			[comment_content] => comment text
			[comment_karma] => 0
			[comment_approved] => 1
			[comment_agent] =>
			[comment_type] =>
			[comment_parent] => 7989
			[user_id] => 1
			[comment_subscribe] => N
		)

	[1] => stdClass Object
		(
			Similar data as in object 0
		)
)

Or a number when specified to get the count of comments.

Usage Template

$args = array(
	'author_email'        => '',
	'author__in'          => '',
	'author__not_in'      => '',
	'include_unapproved'  => '',
	'fields'              => '',
	'comment__in'         => '',
	'comment__not_in'     => '',
	'karma'               => '',
	'number'              => '',
	'offset'              => '',
	'no_found_rows'       => true,
	'orderby'             => '',
	'order'               => 'DESC',
	'parent'              => '',
	'post_author__in'     => '',
	'post_author__not_in' => '',
	'post_id'             => 0,
	'post__in'            => '',
	'post__not_in'        => '',
	'post_author'         => '',
	'post_name'           => '',
	'post_parent'         => '',
	'post_status'         => '',
	'post_type'           => '',
	'status'              => 'all',
	'type'                => '',
	'type__in'            => '',
	'type__not_in'        => '',
	'user_id'             => '',
	'search'              => '',
	'count'               => false,
	'meta_key'            => '',
	'meta_value'          => '',
	'meta_query'          => '',
	'date_query'          => null, // See WP_Date_Query
	'hierarchical'        => false,
	'update_comment_meta_cache'  => true,
	'update_comment_post_cache'  => false,
);

if( $comments = get_comments( $args ) ){
	foreach( $comments as $comment ){
		// actions
	}
}

Usage

$comments = get_comments( $args );
foreach( $comments as $comment ){
	// output
}

Arguments of parameter $args

author_email(string)
email of the comment author whose comments need to be retrieved.
Default: ''
author__in(number/array)
ID of the author whose comments need to be retrieved. Multiple author IDs can be specified in an array. The user_id field is used in the query.
Default: ''
author__not_in(number/array)
ID of the author whose comments need to be excluded. Multiple author IDs can be specified in an array. The user_id field is used in the query.
Default: ''
comment__in(array/number)
ID of the comments to be retrieved.
Default: ''
comment__not_in(array/number)
ID of the comments to be excluded.
Default: ''
count(true/false)
If true, the function will return the total number of comments. If false, an array of comment objects.
Default: false
include_unapproved(array)
Array of IDs or emails of users whose unapproved comments will be included in the result, regardless of the status specified in the status parameter.
Default: ''
karma(number)
Get comments with the specified karma number.
Default: ''
parent(number)
ID of the comment whose child comments need to be retrieved. Specify the ID and the query will be built using the comment_parent=specified number field.
If the hierarchical parameter is enabled, nested comments will also be included in the result (not just those specified in this parameter)
Default: ''
parent__in(array)
Array of IDs of comments whose child comments need to be retrieved. Same as parent, but multiple IDs are specified at once.
Default: array()
parent__not_in(array)
ID of comments whose child comments should NOT be retrieved. The opposite of the parent__in parameter.
Default: array()
post_author(number)
ID of the post author whose comments need to be retrieved. The post_author field from the wp_posts table is used in the query.
Default: ''
post_author__in(number/array)
ID of post authors whose comments need to be retrieved. Multiple author IDs can be specified in an array.
post_author__not_in(number/array)
ID of post authors whose comments should NOT be retrieved. Multiple author IDs can be specified in an array.
Default: ''
post_id(number)
ID of the post/page. If this parameter is specified, the function will return only comments for the specified post or page.
Default: ''
post__in(array)
ID of posts whose comments need to be retrieved.
Default: ''
post__not_in(array)
ID of posts whose comments should be excluded.
Default: ''
post_status(string)
Status of the post. Comments from posts with this status will be retrieved. For example publish.
Default: ''
post_type(string)
Type of post. Comments from posts with this type will be retrieved. For example page.
Default: ''
post_name(string)
Name of the post (slug of the post) whose comments need to be retrieved.
Default: ''
post_parent(number)
ID of the post whose child comments need to be retrieved.
Default: ''
Search conditions based on which comments will be retrieved.
Default: ''
status(string)

Will return comments with this status. Can take the following parameters:

  • all - all comments
  • hold - unapproved comments
  • approve - approved comments
  • spam - spam
  • trash - trash
  • post-trashed - comments from posts in the trash

Default: 'all'

orderby(string/array)

Field from the database table by which the output should be sorted. Multiple fields can be specified using space or comma. Metadata of the comment can also be specified:

Fields from the main table (comments):

  • comment_agent
  • comment_approved
  • comment_author
  • comment_author_email
  • comment_author_IP
  • comment_author_url
  • comment_content
  • comment_date
  • comment_date_gmt
  • comment_ID
  • comment_karma
  • comment_parent
  • comment_post_ID
  • comment_type
  • user_id

Meta-fields. The $meta_key parameter must be set for this:

  • meta_value
  • meta_value_num

To sort by a specific meta-field from the $meta_query parameter, specify the index for the $meta_query request, and write that index here.

Multiple fields can be specified in an array. In this case, the index should be the name of the field, and the value should be the sorting direction. For example: array('comment_date'=>'ASC', 'comment_karma'=>'DESC') More details read here.

You can specify false, array() or 'none' to disable the ORDER BY part of the query.

Default: 'comment_date_gmt'

order(string)
Sorting order: ASC (123), DESC (321). Ignored if an associative array is specified in orderby.
Default: DESC
number(number)
Limit on the number of comments to display (specify the max number). Leave empty to get all comments.
Default: ''
offset(number)
Number of comments to skip from the beginning (top of the result). Used to build the SQL LIMIT part of the query. Used for pagination.
Default: 0
no_found_rows(boolean)
Whether to disable SQL_CALC_FOUND_ROWS in the query.
Default: true
meta_key(string)
Get comments with the specified meta key.
Default: ''
meta_value(string)
Get comments with the specified meta field value. The meta_key parameter must be specified.
Default: ''
meta_query(array)
For creating complex queries on metadata. Replaces the meta_key and meta_value parameters. Works similarly to meta_query in WP_Query.
Default: ''
date_query(array)
Date filter for comments. See WP_Date_Query
Default: null
fields(string)
Fields that will be returned. Can be ids - will get only comment IDs, or empty - will get all fields.
Default: ''
type(string/array)
Type of comments to retrieve. Multiple types can be specified in an array. Can be: comment (equivalent to ''), pings (includes pingback and trackback), or any other arbitrary type.
Default: '' (comment)
type__in(string/array)
Get only comments with the specified type.
Default: ''
type__not_in(string/array)
Get all comments except those with the specified type.
Default: ''
user_id(number)
Will return only comments from the specified user. Equivalent to the author__in parameter.
Default: ''
hierarchical(string/boolean)

Whether to include child comments in the result. The following parameters can be specified:

  • 'threaded' — will return a tree with all child comments. Child comments will be added to the $children property of the first (highest) WP_Comment object.

  • 'flat' — will return a "flat" array, comments and their child comments.

  • false — child comments will not be included in the result.

The parameter is ignored (set to false) when $fields = 'ids' or 'counts'.

Default: false

update_comment_meta_cache(boolean)
Whether to reset the meta-cache for the retrieved comments?
Default: true
update_comment_post_cache(boolean)
Whether to reset the meta-cache for the posts of the comments?
Default: false

When using parameters of the type post_*, the query is built based on the wp_posts table. For example, if post_author__in is specified, all comments from posts whose authors are the specified users will be retrieved.

However, if author__in is specified, individual comments from the specified users will be retrieved.

Added in version 4.4.0. Sorting by the comment__in field. Parameters: $update_comment_meta_cache, $no_found_rows, $hierarchical, $update_comment_post_cache, $parent__in, $parent__not_in.

Examples

3

#1 Outputs all comments on post 15 (including spam and unapproved)

$comments = get_comments( 'post_id=15' );

foreach( $comments as $comment ){

	echo( $comment->comment_author );
}
1

#2 Creating comment pagination

The code below shows how to display user comments with pagination links in WordPress. To do this, we need to use the WP_Comment_Query class.

Suppose we display comments on page /user-comments and we will use GET parameter ?pagenum=10 to add pagination page number. We are going to output 50 comments per page. We are going to use function paginate_links() to create HTML code for pagination links.

$per_page = 50;
$pagenum = $_GET['pagenum'] ?? 1;
$offset = ($pagenum - 1) * $per_page;
$paged_url_patt = home_url( preg_replace( '/[?&].*/', '', $_SERVER['REQUEST_URI'] ) ) .'?pagenum=%#%';

$query    = new WP_Comment_Query;
$comments = $query->query( [
	'order'   => 'DESC',
	'user_id' => $user_id,
	'offset'  => $offset,
	'number'  => $per_page,
	'no_found_rows'  => false,
] );

//$total_comments = (int) $query->found_comments;
$max_pages      = (int) $query->max_num_pages;

$paginate_links = paginate_links( [
	'base'    => $paged_url_patt,
	'current' => $pagenum,
	'total'   => $max_pages
] );

echo $paginate_links;

The result will be the following HTML code:

<a class="prev page-numbers" href="https://example.com/profile/comments?pagenum=2">← Prev</a>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=1">1</a>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=2">2</a>
<span aria-current="page" class="page-numbers current">3</span>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=4">4</a>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=5">5</a>
<span class="page-numbers dots">…</span>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=75">75</a>
<a class="next page-numbers" href="https://example.com/profile/comments?pagenum=4">Next →</a>

0

#3 Show 5 unapproved comments.

$comments = get_comments( [
	'status'  => 'hold',
	'number'  => '5',
	'post_id' => 1, // correctly post_id, not post_ID
] );

foreach( $comments as $comment ){
	echo $comment->comment_author . '<br />' . $comment->comment_content;
}
0

#4 Display the number of comments on the post

$comments = get_comments( [
	'post_id' => 1, // use post_id, not post_ID
	'count' => true // returns only count
] );

echo $comments;
0

#5 Display the number of the user comments

$args = array(
	'user_id' => 1,
	'count'   => true
);

$comments = get_comments( $args );

echo $comments;
0

#6 Display the user's comments.

$args = array(
	'user_id' => 1, // user ID
);

$comments = get_comments( $args );

foreach( $comments as $comment ){
	echo $comment->comment_author . '<br />' . $comment->comment_content;
}
0

#7 Delete, in a row, identical comments.

Comparing the author and the content of the comment.

// get all comments with empty argument number
$all_comments = get_comments( [
	'status' => 'approve',
	'number' => '', 
] );

// array that will contain the IDs of duplicate comments
$comment_ids_to_delete = [];

foreach( $all_comments as $k => $c ){

	$kk = $k-1; // Previous comment index in the $all_comments array
	$pc = $all_comments[ $kk ]; // previous comment object

	// If the author and content are the same, add the comment to the array for deletion
	if( 
		$pc->comment_author === $c->comment_author 
		&& 
		$pc->comment_content === $c->comment_content 
	){
		$comment_ids_to_delete[] = $pc->comment_ID;
	}
}

// Delete comments by ID
foreach( $comment_ids_to_delete as $comm_id ){
	wp_delete_comment( $comm_id );
}
0

#8 Get the latest comments in a list style.

This code gets the last 10 comments as a UL list. Where the comment text is shortened to 50 characters and is a link to the comment itself:

$args = array(
	'number'  => 10,
	'orderby' => 'comment_date',
	'order'   => 'DESC',
	'type' => '', // only comments, no pings, etc...
);

if( $comments = get_comments( $args ) ){

	echo '<ul>';

	foreach( $comments as $comment ){
		$comm_link = get_comment_link( $comment->comment_ID ); // can be a heavy request ...
		$comm_short_txt = mb_substr( strip_tags( $comment->comment_content ), 0, 50 ) .'...';

		echo '<li>'. $comment->comment_author .': <a rel="nofollow" href="'. $comm_link .'">'. $comm_short_txt .'</a></li>';
	}

	echo '</ul>';
}

/*
Data in $comment object
stdClass Object
	[comment_ID]            => 9727
	[comment_post_ID]       => 477
	[comment_author]        => Andrew
	[comment_author_email]  => [email protected]
	[comment_author_url]    =>
	[comment_author_IP]     => 178.45.177.200
	[comment_date]          => 2015-22-01 00:27:04
	[comment_date_gmt]      => 2015-22-28 21:27:04
	[comment_content]       => comment text
	[comment_karma]         => 0
	[comment_approved]      => 1
	[comment_agent]         => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0)
	[comment_type]          =>
	[comment_parent]        => 9724
	[user_id]               => 313

*/
0

#9 An example of getting child comments as a tree

An example of how the parameter 'hierarchical' => 'threaded' works:

$comments = get_comments( [
	'parent'       => 22384,
	'hierarchical' => 'threaded',
] );

/* Result (some fields of WP_Comment object are removed for clarity):
Array
	[22986] => WP_Comment Object
		[comment_ID]           => 22986
		[comment_post_ID]      => 8342
		[comment_author]       => camp
		[comment_date]         => 2018-04-11 19:07:08
		[comment_content]      => Added.
		[comment_type]         =>
		[comment_parent]       => 22430
		[populated_children:protected] => 1
		[children:protected] => Array
			[22998] => WP_Comment Object
				[comment_ID]           => 22998
				[comment_post_ID]      => 8342
				[comment_author]       => Maxim
				[comment_date]         => 2018-04-12 12:15:25
				[comment_content]      => Works great. Thank you!
				[comment_type]         =>
				[comment_parent]       => 22986
				[populated_children:protected] => 1
				[children:protected] => Array
					[23035] => WP_Comment Object
						[comment_ID]                   => 23035
						[comment_post_ID]              => 8342
						[comment_author]               => camp
						[comment_date]                 => 2018-04-16 15:36:00
						[comment_content]              => Thanks for the feedback!
						[comment_type]                 =>
						[comment_parent]               => 22998
						[children:protected]           =>
						[populated_children:protected] => 1

	[22982] => WP_Comment Object
			[comment_ID]            => 22982
			[comment_post_ID]       => 8342
			[comment_author]        => Maxim
			[comment_date]          => 2018-04-11 12:12:00
			[comment_content]       => > Great, if we could also write the output of the total rating.
			[comment_type]          =>
			[comment_parent]        => 22430
			[populated_children:protected] => 1
			[children:protected]    => Array
				[22985] => WP_Comment Object
					[comment_ID]            => 22985
					[comment_post_ID]       => 8342
					[comment_author]        => camp
					[comment_date]          => 2018-04-11 19:05:57
					[comment_content]       => Hello. Judging by the question, you don't need advice, you need to make a ready-made one.
					[comment_type]          =>
					[comment_parent]        => 22982
					[children:protected]    =>
					[populated_children:protected] => 1
*/
0

#10 Get comments via WP_Comment_Query class

This kind of query can be useful when we need to access the properties of the object WP_Comment_Query.

For example, in the properties we can see the query that is obtained with the specified query parameters.

$args = [
	'meta_query'   => [
		[
			'key'     => 'condition',
			'value'   => 'to_delete'
		]
	],
	'date_query' => [
		[ 'before' => '5 month ago' ]
	],
	'orderby' => [ 'comment_ID' => 'DESC' ],
	'number'  => 100
];
$query = new WP_Comment_Query;
$comments = $query->query( $args );

// output the query
echo $query->request;

/*
SELECT  wp_comments.comment_ID FROM wp_comments
	INNER JOIN wp_commentmeta ON ( wp_comments.comment_ID = wp_commentmeta.comment_id )
	WHERE ( ( comment_approved = '0' OR comment_approved = '1' ) )
	AND (
		( wp_commentmeta.meta_key = 'condition' AND wp_commentmeta.meta_value = 'to_delete' )
	)
	AND (
		wp_comments.comment_date < '2020-02-26 11:48:03'
	)
	GROUP BY wp_comments.comment_ID
	ORDER BY wp_comments.comment_ID DESC
	LIMIT 0,100
*/
0

#11 Get comments from last 4 weeks

$args = array(
	'date_query' => array(
		'after' => '4 weeks ago',
		'before' => 'tomorrow',
		'inclusive' => true,
	),
);

$comments = get_comments( $args );

foreach ( $comments as $comment ) {
	// Output comments etc here
}
0

#12 Get all comments of two post types:

$paged = get_query_var( 'page' ) ?: 1;

$args = array(
	'number'    => 5,
	'post_type' => array( 'property', 'page' ),
	'paged' => $paged,
	'parent' => 0,
);

$comments = get_comments( $args );
0

#13 Get child comment of parent comment

$args = array(
	'parent'       => $comment->comment_ID, //Comment ID '64'
	'hierarchical' => true,
	'status'       => 'approve',
);

$child_comments = get_comments( $args );

or you can use get_children()

$comment->get_children()

Changelog

Since 2.7.0 Introduced.

get_comments() code WP 6.9.1

function get_comments( $args = '' ) {
	$query = new WP_Comment_Query();
	return $query->query( $args );
}