Using WordPress ‘get_comment_excerpt’ PHP filter

The get_comment_excerpt WordPress PHP filter allows you to modify the comment excerpt displayed on your website.

Usage

add_filter('get_comment_excerpt', 'your_custom_function', 10, 3);
function your_custom_function($excerpt, $comment_id, $comment) {
    // your custom code here
    return $excerpt;
}

Parameters

  • $excerpt (string) – The comment excerpt text.
  • $comment_id (string) – The comment ID as a numeric string.
  • $comment (WP_Comment) – The comment object.

More information

See WordPress Developer Resources: get_comment_excerpt

Examples

Truncate comment excerpt length

Truncate the comment excerpt to a maximum of 30 characters.

add_filter('get_comment_excerpt', 'truncate_comment_excerpt', 10, 3);
function truncate_comment_excerpt($excerpt, $comment_id, $comment) {
    $excerpt = substr($excerpt, 0, 30) . '...';
    return $excerpt;
}

Add author name to excerpt

Prepend the author’s name to the comment excerpt.

add_filter('get_comment_excerpt', 'prepend_author_to_excerpt', 10, 3);
function prepend_author_to_excerpt($excerpt, $comment_id, $comment) {
    $author = $comment->comment_author;
    $excerpt = $author . ' says: ' . $excerpt;
    return $excerpt;
}

Remove all links from the comment excerpt.

add_filter('get_comment_excerpt', 'remove_links_from_excerpt', 10, 3);
function remove_links_from_excerpt($excerpt, $comment_id, $comment) {
    $excerpt = preg_replace('/<a[^>]*>(.*)<\/a>/iU', '', $excerpt);
    return $excerpt;
}

Replace specific words in comment excerpt

Replace specific words in the comment excerpt.

add_filter('get_comment_excerpt', 'replace_words_in_excerpt', 10, 3);
function replace_words_in_excerpt($excerpt, $comment_id, $comment) {
    $search = array('badword1', 'badword2');
    $replace = array('goodword1', 'goodword2');
    $excerpt = str_replace($search, $replace, $excerpt);
    return $excerpt;
}

Add custom class to comment excerpt

Wrap the comment excerpt in a div with a custom class.

add_filter('get_comment_excerpt', 'add_custom_class_to_excerpt', 10, 3);
function add_custom_class_to_excerpt($excerpt, $comment_id, $comment) {
    $excerpt = '<div class="custom-class">' . $excerpt . '</div>';
    return $excerpt;
}