Posted by & filed under Code Tips.

For a site I’m working on I needed a way to intercept a comment and block if a specific condition wasn’t met. This is what I wound up with.

function preprocess_comment_handler($comment_data) {
        if (/* Some condition if they can comment */) {
            return $comment_data; 
        wp_die('An error message that they cannot comment'); 
add_filter( 'preprocess_comment' , 'preprocess_comment_handler', 1 );

This hooks into the preprocess_comment filter which normally lets you edit comment data before it’s submitted to the database. In this case we’re not doing anything to the comment data if the comment is allowed to pass through, but we’re just killing the process if they’re not allowed to leave a comment.

One thing that I might go back and do later is redirect to an error page rather than just using wp_die. But for now, this is working well enough.

Leave a Reply

Your email address will not be published. Required fields are marked *