0

In wordpress theme i create a custom field with name city in comments form. Its showing and save data well. But problem is that its save the value while its empty. Need Its show error when submit form with empty city field.

i add function for validations but not working.

How to make city comment fields required??

Function.php complete code for city comment field

// Add the fields to comment form
add_filter( 'comment_form_defaults', 'change_comment_form_defaults');
function change_comment_form_defaults( $default ) {
     $commenter = wp_get_current_commenter();
     $default[ 'fields' ][ 'email' ] .= '<p class="comment-form-author">' .
                                        '<label for="city">'. __('City') . '</label>
                                        <span class="required">*</span>
                                        <input id="city" name="city" size="30" type="text" /></p>';
return $default;
}

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

// And save the comment meta
add_action( 'comment_post', 'save_comment_meta_data' );
function save_comment_meta_data( $comment_id ) {
      add_comment_meta( $comment_id, 'city', $_POST[ 'city' ] );
}

// Retrieve and display comment meta
add_filter( 'get_comment_author_link', 'attach_city_to_author' );
function attach_city_to_author( $author ) {
       $city = get_comment_meta( get_comment_ID(), 'city', true );
       if ( $city )
            $author .= " ($city)";
       return $author;
}
1

Please add below code into your current theme's function.php

function custom_validate_city() {
    if( empty($_POST[ 'city' ])) // do you url validation here (I am not a regex expert)
        wp_die( __('Error: please enter a city') );
}

add_action('pre_comment_on_post', 'custom_validate_city');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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