2

I have a comment form and in that comment form I've added an extra input field called with the name 'review_title'. When one submits the comment form the comment it's gets inserted perfectly fine and the extra field gets inserted into the comment meta. Want I want to achieve is a server side check when the comment is submitted, that checks if the extra field is empty and if the extra field is empty, then stop the script from posting the comment. Here is my attempt:

This is the form:

<form action="http://localhost/test/wp-comments-post.php" method="post" id="commentform" class="comment-form">
    <p class="comment-form-title">
        <label for="pmg_comment_title">Review Title</label>
        <input type="text" name="review_title" id="pmg_comment_title" />
    </p>
    <p class="comment-form-comment">
        <label for="comment">Comment</label> 
        <textarea id="comment" name="comment" required="required"></textarea> 
    </p>
    <input name="submit" type="submit" id="submit" value="Post Comment" />
</form>

This is the function I tried to do this with:

function verify_comment_meta_data( $commentdata ) {
if (!isset($_POST['review_title']))
        wp_die( __( 'Error: please fill the required field (city).' ) );
    return $commentdata;
}
add_filter( 'preprocess_comment', 'verify_comment_meta_data' );

Unfortunately this doesn't do anything at all, if I leave the 'review_title' field blank, it'll still post the comment just without that field.

So my question is how to stop the comment submit, if the 'review_title' field is empty?

1 Answer 1

4

If you use wp-comments-post.php it would be better to customize comment_form by hook comment_form_default_fields, I don't know why you create the new one. But as per of your functions you can handle it like this

add_filter( 'preprocess_comment', 'verify_comment_meta_data', 1, 1 );
function verify_comment_meta_data( $commentdata )
{
    $commentdata['review_title'] = ( ! empty ( $_POST['review_title'] ) ) ? sanitize_text_field( $_POST['review_title'] ) : false;
    if ( ! $commentdata['review_title'] )
        wp_die( __( '<strong>ERROR</strong>: please fill the required fields ( city ).', 'textdomain' ) );
     return $commentdata;
}

Actuallly as WordPress comments workflow, the error messages could be handled by fire pre_comment_on_post, check_comment_flood, or pre_comment_approved.

1
  • Thanks! I didn't know !isset() was different from empty()
    – Noob17
    Commented Mar 7, 2016 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.