GeneratorsQueryComment Query Builder

Comment Query Builder

Comment queries by status, type, post and hierarchy — with the "all includes spam" and hierarchical-counts-threads gotchas called out before they ship.

comment-query.php
Saved just now
Status and type
Only real comments. Pingbacks and trackbacks are excluded, which is what a front-end list wants.
Scope
Order and shape
Count only
Returns a single number instead of rows.
Prime the comment meta cache
One query for all comment meta instead of one per comment.
no_found_rows
Skips the total count when you are not paginating.
The class, with a loop that links each comment back to its post.
// Generated with WP CodeKit — powered by GrowQuest (https://growquest.io).
$query = new WP_Comment_Query();

$comments = $query->query( array(
	'status'  => 'approve',
	'type'    => 'comment',
	'number'  => 10,
	'orderby' => 'comment_date_gmt',
) );

if ( $comments ) {
	echo '<ul class="recent-comments">';

	foreach ( $comments as $comment ) {
		printf(
			'<li><a href="%1$s">%2$s</a> on %3$s<p>%4$s</p></li>',
			esc_url( get_comment_link( $comment ) ),
			esc_html( get_comment_author( $comment ) ),
			esc_html( get_the_title( $comment->comment_post_ID ) ),
			esc_html( wp_trim_words( $comment->comment_content, 20 ) )
		);
	}

	echo '</ul>';
} else {
	esc_html_e( 'No comments yet.', 'mytheme' );
}