The comment_excerpt WordPress PHP filter allows you to modify the displayed comment excerpt text.
Usage
add_filter('comment_excerpt', 'your_custom_function', 10, 2);
function your_custom_function($comment_excerpt, $comment_id) {
// your custom code here
return $comment_excerpt;
}
Parameters
$comment_excerpt(string) – The comment excerpt text.$comment_id(string) – The comment ID as a numeric string.
More information
See WordPress Developer Resources: comment_excerpt
Examples
Add “Read more” to comment excerpts
This example adds a “Read more” link to the end of comment excerpts.
add_filter('comment_excerpt', 'add_read_more_to_comment_excerpt', 10, 2);
function add_read_more_to_comment_excerpt($comment_excerpt, $comment_id) {
// Add "Read more" link to the comment excerpt
$comment_excerpt .= ' <a href="' . get_comment_link($comment_id) . '">Read more</a>';
return $comment_excerpt;
}
Limit comment excerpt length
This example limits the length of comment excerpts to 50 characters.
add_filter('comment_excerpt', 'limit_comment_excerpt_length', 10, 2);
function limit_comment_excerpt_length($comment_excerpt, $comment_id) {
// Limit the comment excerpt length to 50 characters
$comment_excerpt = wp_trim_words($comment_excerpt, 50);
return $comment_excerpt;
}
Replace specific words in comment excerpts
This example replaces the word “bad” with “***” in comment excerpts.
add_filter('comment_excerpt', 'replace_bad_word_in_comment_excerpt', 10, 2);
function replace_bad_word_in_comment_excerpt($comment_excerpt, $comment_id) {
// Replace the word "bad" with "***"
$comment_excerpt = str_replace('bad', '***', $comment_excerpt);
return $comment_excerpt;
}
Add a custom CSS class to comment excerpts
This example adds a custom CSS class to comment excerpts.
add_filter('comment_excerpt', 'add_custom_class_to_comment_excerpt', 10, 2);
function add_custom_class_to_comment_excerpt($comment_excerpt, $comment_id) {
// Add a custom CSS class to the comment excerpt
$comment_excerpt = '<span class="custom-class">' . $comment_excerpt . '</span>';
return $comment_excerpt;
}
Add the author name to comment excerpts
This example adds the author name to the beginning of comment excerpts.
add_filter('comment_excerpt', 'add_author_name_to_comment_excerpt', 10, 2);
function add_author_name_to_comment_excerpt($comment_excerpt, $comment_id) {
// Get the comment author name
$comment_author = get_comment_author($comment_id);
// Add the author name to the beginning of the comment excerpt
$comment_excerpt = $comment_author . ' says: ' . $comment_excerpt;
return $comment_excerpt;
}