pre_comment_content is a WordPress PHP filter that allows you to modify the comment content before it is saved in the database.
Usage
add_filter('pre_comment_content', 'your_custom_function', 10, 1);
function your_custom_function($comment_content) {
// your custom code here
return $comment_content;
}
Parameters
$comment_content(string): The comment content to be filtered.
More information
See WordPress Developer Resources: pre_comment_content
Examples
Remove HTML Tags
Strip all HTML tags from the comment content.
add_filter('pre_comment_content', 'remove_html_tags', 10, 1);
function remove_html_tags($comment_content) {
$comment_content = strip_tags($comment_content);
return $comment_content;
}
Replace Bad Words
Replace specific bad words with asterisks.
add_filter('pre_comment_content', 'replace_bad_words', 10, 1);
function replace_bad_words($comment_content) {
$bad_words = array('badword1', 'badword2');
$replacement = '*****';
$comment_content = str_ireplace($bad_words, $replacement, $comment_content);
return $comment_content;
}
Convert URLs to Links
Automatically convert URLs within the comment content to clickable links.
add_filter('pre_comment_content', 'convert_urls_to_links', 10, 1);
function convert_urls_to_links($comment_content) {
$comment_content = make_clickable($comment_content);
return $comment_content;
}
Add a Signature
Automatically add a signature to the end of each comment.
add_filter('pre_comment_content', 'add_signature', 10, 1);
function add_signature($comment_content) {
$signature = ' -- Thanks for commenting!';
$comment_content .= $signature;
return $comment_content;
}
Limit Comment Length
Limit the comment content to a specific number of characters.
add_filter('pre_comment_content', 'limit_comment_length', 10, 1);
function limit_comment_length($comment_content) {
$max_length = 200;
$comment_content = mb_substr($comment_content, 0, $max_length);
return $comment_content;
}