Using WordPress ‘get_comment_excerpt()’ PHP function

The get_comment_excerpt() WordPress PHP function retrieves the excerpt of a given comment, returning a maximum of 20 words with an ellipsis appended if necessary.

Usage

get_comment_excerpt( $comment_id );

Example:
Input:

get_comment_excerpt( 42 );

Output:

"This is a sample comment..."

Parameters

  • $comment_id (int|WP_Comment): Optional, WP_Comment or ID of the comment for which to get the excerpt. Default current comment.

More information

See WordPress Developer Resources: get_comment_excerpt()

Examples

Display comment excerpt for a specific comment

Display the comment excerpt of a specific comment with ID 42.

$comment_excerpt = get_comment_excerpt( 42 );
echo $comment_excerpt;

Display comment excerpts in a loop

Loop through an array of comment IDs and display their comment excerpts.

$comment_ids = array( 1, 2, 3, 4, 5 );

foreach ( $comment_ids as $comment_id ) {
    $comment_excerpt = get_comment_excerpt( $comment_id );
    echo "<p>$comment_excerpt</p>";
}

Display comment excerpt with a custom length

Create a custom function to display a comment excerpt with a specified maximum length.

function custom_get_comment_excerpt( $comment_id, $length = 20 ) {
    $comment_content = get_comment_text( $comment_id );
    $excerpt = wp_trim_words( $comment_content, $length, '...' );

    return $excerpt;
}

$custom_comment_excerpt = custom_get_comment_excerpt( 42, 10 );
echo $custom_comment_excerpt;

Display comment excerpt within a comments loop

Display comment excerpts within the WordPress comments loop.

if ( have_comments() ) {
    while ( have_comments() ) {
        the_comment();
        $comment_excerpt = get_comment_excerpt();
        echo "<p>$comment_excerpt</p>";
    }
}

Display the comment excerpt with a “Read more” link that leads to the full comment.

$comment_id = 42;
$comment_excerpt = get_comment_excerpt( $comment_id );
$comment_link = get_comment_link( $comment_id );

echo "<p>$comment_excerpt <a href=\"$comment_link\">Read more</a></p>";