WordPress Form Tutorial (Part 3)


The form data needs to be validated on the server, even if it’s validated with Javascript on the client. We’ll do that with our wp_form_demo_validate function. But first, we know we’re going to need a method to set error messages in the event we encounter some invalid data. So let’s write that method first.

This method is a setter and a getter. It uses a static variable $message, which maintains its value like a global variable, but can only be accessed within the containing function. On return, the function wraps the message in a div for CSS formatting.

1
2
3
4
5
6
7
function wp_form_demo_error_message( $msg = '' ) {
  static $message;
  if ( ! empty( $msg ) ) {
    $message .= ( ! empty( $message ) ? '<br />'."\n" : '' ) . $msg;
  }
  return empty( $message ) ? '' : '<div class="error-message">'. $message .'</div>'."\n";
}

Now we can validate the data.

For brierty, we’re just going to check if the fields are empty. Obviously, in a production application, you should validate the email address.

On lines 3 and 6, we set error messages if the fields are empty. On line 9, we use the return valid from our wp_form_demo_error_message function to determine the return value. If there is no error message, return true. Else, return false.

1
2
3
4
5
6
7
8
9
10
function wp_form_demo_validate($form_data) {
  if ( empty( $form_data->username )) {
    wp_form_demo_error_message( 'Name can not be empty' );
  }
  if ( empty( $form_data->email ) ) {
    wp_form_demo_error_message( 'Email can not be empty' );
  }

  return wp_form_demo_error_message() == '';
}

We can now validate the data in wp_form_demo — the shortcode callback.

  1. If the form has not been submitted…
  2. Display an empty form
  3. Else…
  4. Cast the POST data to an object and store it in $post_data.
  5. Validate the form data. If it’s valid, submit the data. (In the function wp_form_demo_submit function, you’ll submit the data the database.)
  6. Add a success message to the form to be displayed.
  7. Display the form with the entered values.
  8. Else, the validation failed
  9. Add the error message(s) to the form.
  10. Display the form with the user entered values.
  11. Return the form, which will replace the shortcode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function wp_form_demo( $atts ) {
  $form = '<h2>Form Demo</h2>'."\n";
 
  if ( ! isset( $_POST['wp-custom-form-submitted'] ) ) {
    $form .= wp_form_demo_form();
  }
  else {
    $form_data = (object)$_POST;
    if ( wp_form_demo_validate( $form_data ) ) {
      wp_form_demo_submit( $form_data );
      $form .= '<div>Your form has been submitted.</div>'."\n";
      $form .= wp_form_demo_form( $form_data );
    }
    else {
      $form .= wp_form_demo_error_message();
      $form .= wp_form_demo_form( $form_data );
    }
  }
  return $form;
}

That’s pretty much all there is to it!