Using WordPress ‘comment_save_pre’ PHP filter

The comment_save_pre WordPress PHP filter allows you to modify the comment content before it is saved in the database.

Usage

add_filter('comment_save_pre', 'your_custom_function');
function your_custom_function($comment_content) {
    // your custom code here
    return $comment_content;
}

Parameters

  • $comment_content (string): The content of the comment being saved.

More information

See WordPress Developer Resources: comment_save_pre

Examples

Remove HTML tags from comment content

Remove any HTML tags from the comment content before saving it to the database.

add_filter('comment_save_pre', 'remove_html_tags_from_comments');
function remove_html_tags_from_comments($comment_content) {
    $comment_content = strip_tags($comment_content);
    return $comment_content;
}

Replace bad words with asterisks

Replace a list of bad words with asterisks in the comment content before saving it.

add_filter('comment_save_pre', 'replace_bad_words');
function replace_bad_words($comment_content) {
    $bad_words = array('badword1', 'badword2', 'badword3');
    $replacement = '****';
    $comment_content = str_replace($bad_words, $replacement, $comment_content);
    return $comment_content;
}