1. Skip to Navigation
  2. Skip to Content
our blog

WordPress: How To Change Comment Excerpt Length

I recently needed to output a list of comments and bumped into a little trouble trying to output the comment excerpt. Usually I would use the built-in comment_excerpt() function but I only needed 10 words instead of the 20 that is hard-coded. I put together a little function that I found helpful and thought I would share.

I started with get_comment_excerpt() from line ~407 of wp-includes/comment-template.php and pasted it into my_name/functions.php to be modified.

Here’s what I ended up with:

function my_get_comment_excerpt($comment_ID = 0, $num_words = 20) {
	$comment = get_comment( $comment_ID );
	$comment_text = strip_tags($comment->comment_content);
	$blah = explode(' ', $comment_text);
	if (count($blah) > $num_words) {
		$k = $num_words;
		$use_dotdotdot = 1;
	} else {
		$k = count($blah);
		$use_dotdotdot = 0;
	$excerpt = '';
	for ($i=0; $i<$k; $i++) {
		$excerpt .= $blah[$i] . ' ';
	$excerpt .= ($use_dotdotdot) ? '...' : '';
	return apply_filters('get_comment_excerpt', $excerpt);

And here’s a little code to output a list of comments using this function:

	$comments = get_comments();
	foreach($comments as $c) :
	<a href="<?php echo get_permalink($c->comment_post_ID); ?>">
		<?php /* output 10 words of comment */ ?>
		<p><?php echo my_get_comment_excerpt($c->comment_ID, 10); ?></p>		
		<span><?php echo $c->comment_author; ?></span>
		<span><?php echo date("m/j/Y",strtotime($c->comment_date)); ?> </span>

Feel free to ask questions in the comments.

3 Responses to WordPress: How To Change Comment Excerpt Length

  1. gwyn says:

    Thank you! Works like a charm.

  2. s_w_ir says:

    Thanks for sharing. Saved me some time :-)

  3. Ness says:

    Thanks a lot, everything I was looking for and works perfectly.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>