Function for displaying recent comments

I'll start with the fact that comments in WordPress can be retrieved from the database using the function get_comments(). Here's an example from the function description:

# Get the latest comments in a list

This code retrieves the latest 10 comments in a UL list. The comment text is shortened to 50 characters and is linked to the actual comment:

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

if( $comments = get_comments( $args ) ){
	echo '<ul>';
	foreach( $comments as $comment ){
		$comm_link = get_comment_link( $comment->comment_ID ); // potentially heavy query ...
		$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>';
}

/*
$comment = 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_karma] => 0
	[comment_approved] => 1
	[comment_agent] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
	[comment_type] =>
	[comment_parent] => 9724
	[user_id] => 313
)
*/

Change this code according to your needs. If for some reason this option doesn't suit you, then everything below is for you.

Custom function for displaying recent comments

You can also display the latest comments by creating a custom database query:

/**
 * Function for displaying latest comments in WordPress.
 * ver: 0.2
 */
function kama_recent_comments( $args = array() ){
	global $wpdb;

	$def = array(
		'limit'      => 10, // number of comments to display.
		'ex'         => 45, // n characters. Comment text truncation.
		'term'       => '', // category/tag IDs. Include(5,12,35) or exclude(-5,-12,-35) categories. By default - from all categories.
		'gravatar'   => '', // Icon size in px. Show gravatar icon. '' - don't show.
		'user'       => '', // user IDs. Include(5,12,35) or exclude(-5,-12,-35) user comments. By default - all users.
		'echo'       => 1,  // output to screen (1) or return (0).
		'comm_type'  => 'comment', // comment type name
		'meta_query' => '', // WP_Meta_Query
		'meta_key'   => '', // WP_Meta_Query
		'meta_value' => '', // WP_Meta_Query
		'url_patt'   => '', // comment link optimization. Example: '%s?comments#comment-%d' placeholders will be replaced with $post->guid and $comment->comment_ID
	);

	$args = wp_parse_args( $args, $def );
	extract( $args );

	$AND = '';

	// POSTS
	if( $term ){
		$cats = explode( ',', $term );
		$cats = array_map( 'intval', $cats );

		$CAT_IN = ( $cats[ key($cats) ] > 0 ); // from categories or not

		$cats = array_map( 'absint', $cats ); // remove negatives
		$AND_term_id = 'AND term_id IN ('. implode(',', $cats) .')';

		$posts_sql = "SELECT object_id FROM $wpdb->term_relationships rel
		LEFT JOIN $wpdb->term_taxonomy tax ON (rel.term_taxonomy_id = tax.term_taxonomy_id) WHERE 1 $AND_term_id ";

		$AND .= ' AND comment_post_ID '. ($CAT_IN ? 'IN' : 'NOT IN') .' ('. $posts_sql .')';
	}

	// USERS
	if( $user ){
		$users = explode(',', $user );
		$users = array_map('intval', $users );

		$USER_IN = ( $users[ key($users) ] > 0 );

		$users = array_map('absint', $users );

		$AND .= ' AND user_id '. ($USER_IN ? 'IN' : 'NOT IN') .' ('. implode(',', $users) .')';
	}

	// WP_Meta_Query
	$META_JOIN = '';
	if( $meta_query || $meta_key || $meta_value ){
		$mq = new WP_Meta_Query( $args );
		$mq->parse_query_vars( $args );
		if( $mq->queries ){
			$mq_sql = $mq->get_sql('comment', $wpdb->comments, 'comment_ID' );
			$META_JOIN = $mq_sql['join'];
			$AND .= $mq_sql['where'];
		}
	}

	$sql = $wpdb->prepare("SELECT * FROM $wpdb->comments LEFT JOIN $wpdb->posts ON (ID = comment_post_ID ) $META_JOIN
	WHERE comment_approved = '1' AND comment_type = %s $AND ORDER BY comment_date_gmt DESC LIMIT %d", $comm_type, $limit );

	//die( $sql );
	$results = $wpdb->get_results( $sql );

	if( ! $results )
		return 'No comments.';

	// HTML
	$out = $grava = '';
	foreach ( $results as $comm ){
		if( $gravatar )
			$grava = get_avatar( $comm->comment_author_email, $gravatar );

		$comtext = strip_tags( $comm->comment_content );
		$com_url = $url_patt ? sprintf( $url_patt, $comm->guid, $comm->comment_ID ) : get_comment_link( $comm->comment_ID );

		$length = (int) mb_strlen( $comtext );
		if( $length > $ex )
			$comtext = mb_substr( $comtext, 0, $ex ) .' …';

		$out .= '
		<li>
			'. $grava .' <b>'. strip_tags( $comm->comment_author ) .':</b>
			<a href="'. $com_url .'" title="to post: '. esc_attr( $comm->post_title ) .'">'. $comtext .'</a>
		</li>';
	}

	if( $echo )
		return print $out;
	return $out;
}

Usage Examples

#1 Displaying the latest comments

<ul>
	<?php kama_recent_comments( "limit=10&ex=40" ); ?>
</ul>
  • 10 - the number of comments to be shown.
  • 40 - the number of characters from the comment text to be displayed. The count is done after removing all HTML tags from the text to maintain equal text length.

#2 Comments for posts from specified categories/tags

The function can also include/exclude comments for posts from specified categories/tags/custom taxonomies. The parameter term is responsible for this, and you need to specify the category IDs (you can see them in the "categories" section in the admin panel). To exclude, add a "-" before the ID:

<ul>
	<?php kama_recent_comments("limit=10&ex=40&term=5,10,34"); ?>
</ul>

This will display 10 comments, with a text length of up to 40 characters, for posts from categories 5, 10, and 34. To exclude these categories, the function can be called as follows:

<ul>
	<?php kama_recent_comments("limit=10&ex=40&term=-5,-10,-34"); ?>
</ul>

This will display 10 comments, with a text length of up to 40 characters, for all posts except those from categories 5, 10, and 34.

It is not possible to simultaneously include and exclude categories! However, this is devoid of common sense smile

#3 Return the result

If you need to return the result for further processing in PHP, instead of displaying it on the screen, set the echo parameter to 0:

<?php kama_recent_comments('echo=0'); ?>

#4 Avatars

If you need to include displaying gravatars from the Gravatar service, specify the gravatar parameter as the required avatar size. For example, 20 - activates the display of avatars and will show an avatar with a width and height of 20px.

<ul>
	<?php kama_recent_comments('gravatar=20'); ?>
<ul>