The pre_comment_content hook is a filter hook that allows developers to modify or manipulate the content of a comment before it is saved into the database. This hook is fired after a user submits a comment, but before it is processed and saved into the database.
Developers can use this hook to manipulate the content of comments, for example, to filter out certain keywords or to add custom data to the comment. This hook is particularly useful for developers who want to implement a custom spam filter or content moderation system on their WordPress site.
Here’s an example usage code of the pre_comment_content hook:
function my_custom_comment_filter( $comment_content ) {
// Check if the comment contains a banned keyword
if ( strpos( $comment_content, 'banned keyword' ) !== false ) {
// If it does, replace the banned keyword with a '***'
$comment_content = str_replace( 'banned keyword', '***', $comment_content );
}
// Add custom data to the comment content
$comment_content .= "nn" . 'Custom data: ' . get_current_user_id();
return $comment_content;
}
add_filter( 'pre_comment_content', 'my_custom_comment_filter' );
In this example, we’ve created a function called my_custom_comment_filter
that checks if the comment contains a banned keyword and replaces it with ‘***’. We’ve also added some custom data to the comment content using the get_current_user_id
function. Finally, we’ve added this function as a filter to the pre_comment_content
hook using the add_filter
function.