how to create custom form in wordpress and handle submission

There are cool plugins available that create forms without any programming effort but still many times we need to create custom forms in our WordPress website.

So where to start with? What should be the form action? And where do we handle form submission? How WordPress will detect our custom form is submitted?

These questions comes in mind when you set to go with development of custom form plugin. In this post I will answer all those questions and make you able to create custom form.

Plugin constructor:
First line of constructor method is to hook WordPress’s initfunction. This is useful for intercepting $_GET or $_POSTtriggers because init() runs after WordPress has finished loading but before any headers are sent. Hence this is where we will be processing our form submissions.

On second line we are registering a shortcode that we will be putting in pages to render our form. In this example the shortcode is ‘contact_form’. You will be putting  wherever you want to put your custom form.


 class Contact_Us_Plugin {

public function __construct() 
{
  add_action('init', array($this, 'init'));
 add_shortcode( 'contact_form', array($this,'contact_form_shortcode') );
}
 public function init()
    {
        if(!wp_verify_nonce($_POST['op_contact_nonce_field'], 'op_contact_nonce')){
       
            if (!wp_verify_nonce($_POST['nonce_custom_form'], 'handle_custom_form'))
            {
                die('You are not authorized to perform this action.');
            } else
            {
                $error = null;
                if (empty($_POST['name']))
                {
                    $error = new WP_Error('empty_error', __('Please enter name.', 'tahiryasin'));
                    wp_die($error->get_error_message(), __('CustomForm Error', 'tahiryasin'));
                }
                else
                    die('Its safe to do further processing on submitted data.');
            }
        }else
{
return;
}
    }
 function contact_form_shortcode($atts)
    {   
        	echo "
wp_nonce_field('op_contact_nonce', 'op_contact_nonce_field'); <div class="form-group"> <input id="fname" class="form-control" name="fullname" required="" type="text" placeholder="Your name.." /></div>   <div class="form-group"> <input id="email" class="form-control" name="email" required="" type="email" placeholder="Your Email" /></div>   <div class="form-group"> <input id="subject" class="form-control" name="subject" required="" type="text" placeholder="Subject" /></div>   <div class="form-group"> <textarea id="subject" class="form-control" style="height: 170px;" name="message" placeholder="Write something.."></div> <input name="save" type="submit" value="Submit" /> </form> "; } } $Contact_Us_Plugin = new Contact_Us_Plugin();

Leave a Reply