WordPress Form Tutorial (Part 2)


Now that we have a working plugin and a function stubs, we can add some functionality.

We’ll start by creating the form. The cleanest way to capture HTML is with the two functions: ob_start() and ob_get_clean().

  1. The function takes one parameter: $form_data, which is optional and has a default value of NULL. We can use that later to set default values in the form.
  2. We use the request URI for the action, which works for standard query strings and clean URLs.
  3. Sanitize the data.
  4. Start the output buffer. All data sent to standard out will be captured.
  5. Close the PHP tag and go into HTML mode.
  6. Create the form with standard HTML.
  7. Escape back into PHP mode
  8. Get the contents of and clean the buffer. Return the HTML form.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function wp_form_demo_form($form_data = NULL) {
  $action = esc_url( $_SERVER['REQUEST_URI'] );
  $name = $form_data ? sanitize_text_field( $form_data->username ) : '';
  $email = $form_data ? sanitize_email( $form_data->email ) : '';

  ob_start();
?>
  <form action="<?php echo $action ?>" method="post">
     <input type="hidden" name="wp-custom-form-id" value="form-1" />
     <label for="name">Name:</label>
     <input id="name" type="text" name="username" value="<?php echo $name ?>" />
     <label for="email">Email:</lname>
     <input id="email" type="text" name="email" value="<?php echo $email ?>" />

     <input type="submit" name="wp-custom-form-submitted" value="Submit" />
   </form>
<?php
  return ob_get_clean();
}

Now we can display the form by adding a call to wp_form_demo_form() in the shortcode callback.

1
2
3
4
5
function wp_form_demo() {
  $form = '<h2>Form Demo</h2>'."\n";
  $form .= wp_form_demo_form();
  return $form;
}

At this point, your page will display the form. In the next post, we’ll validate and submit the user data.