Using WordPress ‘comment_text’ PHP filter

The comment_text WordPress PHP filter allows you to modify the text of a comment before it is displayed on the website.

Usage

add_filter('comment_text', 'my_custom_comment_text', 10, 3);
function my_custom_comment_text($comment_text, $comment, $args) {
    // your custom code here
    return $comment_text;
}

Parameters

  • $comment_text (string): The text of the current comment.
  • $comment (WP_Comment|null): The comment object, or null if not found.
  • $args (array): An array of arguments.

More information

See WordPress Developer Resources: comment_text

Examples

Replace bad words in comments

Automatically replace bad words in comments with asterisks.

add_filter('comment_text', 'replace_bad_words', 10, 1);
function replace_bad_words($comment_text) {
    $bad_words = array('badword1', 'badword2');
    $replace = '***';
    $comment_text = str_ireplace($bad_words, $replace, $comment_text);
    return $comment_text;
}

Add a prefix to all comments

Add “Comment: ” as a prefix to all comments.

add_filter('comment_text', 'add_comment_prefix', 10, 1);
function add_comment_prefix($comment_text) {
    return 'Comment: ' . $comment_text;
}