The get_comment_text WordPress PHP filter allows you to modify the text of a comment before it’s displayed on the website.
Usage
add_filter('get_comment_text', 'your_custom_function', 10, 3); function your_custom_function($comment_content, $comment, $args) { // Your custom code here return $comment_content; }
Parameters
- $comment_content (string): Text of the comment.
- $comment (WP_Comment): The comment object.
- $args (array): An array of arguments.
More information
See WordPress Developer Resources: get_comment_text
Examples
Replace bad words in a comment
This example replaces bad words with asterisks before displaying the comment.
add_filter('get_comment_text', 'replace_bad_words', 10, 3); function replace_bad_words($comment_content, $comment, $args) { $bad_words = array('badword1', 'badword2', 'badword3'); $replacement = '****'; $comment_content = str_ireplace($bad_words, $replacement, $comment_content); return $comment_content; }
Highlight author’s comment
This example adds a “highlight” class to the author’s comments.
add_filter('get_comment_text', 'highlight_authors_comment', 10, 3); function highlight_authors_comment($comment_content, $comment, $args) { if ($comment->user_id == get_the_author_meta('ID')) { $comment_content = '<span class="highlight">' . $comment_content . '</span>'; } return $comment_content; }
Add comment number
This example adds a comment number before each comment text.
add_filter('get_comment_text', 'add_comment_number', 10, 3); function add_comment_number($comment_content, $comment, $args) { static $comment_count = 1; $comment_content = "#{$comment_count} " . $comment_content; $comment_count++; return $comment_content; }
Add emojis to the comment text
This example adds a smiley emoji at the end of each comment text.
add_filter('get_comment_text', 'add_emoji_to_comment', 10, 3); function add_emoji_to_comment($comment_content, $comment, $args) { $comment_content .= ' 😃'; return $comment_content; }
Truncate long comments
This example truncates comments that exceed a specified character limit and adds an ellipsis.
add_filter('get_comment_text', 'truncate_long_comments', 10, 3); function truncate_long_comments($comment_content, $comment, $args) { $max_length = 200; if (strlen($comment_content) > $max_length) { $comment_content = substr($comment_content, 0, $max_length) . '...'; } return $comment_content; }