preprocess_comment

Home » Hooks » preprocess_comment

The WordPress hook preprocess_comment is triggered before a comment is saved to the database. This hook can be used to modify the comment data before it is inserted into the database.

There are various use cases of this hook. For example, you can use it to add or modify data in the comment object, validate the comment data, or even block the comment submission.

Here is an example usage code for preprocess_comment:

add_filter( 'preprocess_comment', 'my_preprocess_comment_function' );

function my_preprocess_comment_function( $comment_data ) {
    // Modify the comment data
    $comment_data['comment_content'] = strtoupper( $comment_data['comment_content'] );

    // Validate the comment data
    if ( empty( $comment_data['comment_author'] ) ) {
        wp_die( 'Please enter your name.' );
    }

    // Block the comment submission
    if ( $comment_data['comment_author'] === 'Spam Bot' ) {
        wp_die( 'You are not allowed to comment.' );
    }

    return $comment_data;
}

In this example, we are using the preprocess_comment hook to modify the comment content to uppercase, validate that the comment author is not empty, and block the comment submission if the author’s name is "Spam Bot".

By using the preprocess_comment hook, we can customize the comment submission process to fit our specific needs.

Learn More on WordPress.org

WordPress snippets using the preprocess_comment hook

Register an account to save your snippets or go Pro to get more features.