WordPress Form Tutorial (Part 1)


Many plugins are available for WordPress that allow you to create forms through the GUI without writing any code. But many of them are bloated and contain a lot of features you don’t need. They can slow down your website. And sometimes you need a custom form that can’t be created through an existing plugin.

It’s fairly simple to create a form plugin if you know PHP and the basics of plugins. This tutorial will show you how.

We’re going to use the name wp-form-demo for our plugin and we’ll use the following shortcode [wp-form-demo], which the user can enter into a post.

WordPress provides the add_shortcode( $tag , $func ) shortcode action API to make life easy for developers. You provide it with the shortcode tag and the name of your callback. The shortcode is replace with the text generated by the callback.

Every form should have ‘get form’, ‘validate form’, and ‘submit form’ functions. It’s a good idea to prefix all your functions with the name of the plugin so there are no name collisions. You can also use namespaces to solve that problem, and we’ll get into that in another tutorial.

Our shortcode callback is going to be called wp_form_demo, which will be called when WordPress encounters a shortcode in a post. The other form functions will have a _form, _validate, and _submit appended to wp_form_demo as follows:

<?php
/**
 * Plugin Name: WP Form Demo
 * Description: This plugin demonstrates basic form contruction
 * Author: Your name
 * Version: 0.9
 * Author URI: http://yoursite.com
*/

function wp_form_demo() {
  $form = '<h2>Form Demo</h2>'."\n";
  return $form;
}

add_shortcode( 'wp-custom-form', 'wp_form_demo' );

function wp_form_demo_form( $form_data = NULL ) {
  return '';
}

function wp_form_demo_validate( $form_data ) {
  return true;
}

function wp_form_demo_submit( $form_data ) {

}

You can activate the plugin at this point. The page containing the shortcode should now show “Form Demo” instead of the shortcode.

The next post will fill in the functions and make this plugin functional.