Change the comment form fields from the preprocess_comment hook in WordPress?

Context: When a visitor submits the comment form in WordPress, I want to validate the data in preprocess_comment. If certain parameters are not met, I want to three things to happen:

  1. The comment is not saved
  2. The visitor returns to the page containing the form, its fields are prepopulated with the submitted values
  3. The comment form is altered and an extra form element with a CAPTCHA is added.

I’ve tried to do something like this:

Read More
function myplugin_validate($comment) {
  add_action('comment_form_logged_in_after', 'comment_form_captcha_field');
  return $comment;
}
add_action('preprocess_comment', 'myplugin_validate');

function comment_form_captcha_field() {
  echo "....";
}

This approach won’t work though:

There is no way to stop the flow in preprocess_comment
Since comment_form_captcha_field() is never called, you won’t return to a prepopulated comment form with the user submitted values.

There are of course “dirty” alternatives like storing the submitted values in a session, redirecting the user from preprocess_comment (wp_redirect) and catching the values from the session after reloading the page. Or I could intercept the submit handler through JS and go from there.

I wonder if there is a way to hook onto the comment system in WordPress and do this without resorting to javascript, sessions and the likes.

Related posts

Leave a Reply