How to add a form to a shortcode in WordPress (using PHP and Ajax)

Recently I needed to develop a Shortcode that would display a form, this blog post details what I did. I used Ajax ( which seems the best way to add forms to shortcodes, but I’d welcome any input from other developers on your approach).

So without further ado lets get on with adding a form to a shortcode in WordPress.

We need javascript to handle submission of the form via ajax (this presumes you have jquery available), and handle the response from the server. green_form is the form id.

jQuery( document ).ready(function() {
    // Handler for .ready() called.
    
    
    //
    jQuery(function(){
        jQuery("#green_form").submit(function(event){
            event.preventDefault();
            
            var formOk = true;
            
            // do js validation 
   
            jQuery.ajax({
                url:ajax_object.ajax_url,
                type:'POST',
                data: jQuery(this).serialize() + "&action=green_do_something",
                success:function(response){
                    
                        
                    if(response=="true")
                    {
                       // do something
                    }
                    else{
                        
                        alert('doh something went wrong'); 
                    }
                       

                }

            });
        });
    });


});

 

Next we need the php to handle everything else, you could put this in functions.php (or include from functions.php) or put it into a plugin. The shortcode to include the form in our page or post is [shortcode_with_form] 

The code handles:

  • the output of the shortcode
  • the server side processing of the form (I’ve just created a stub in this example ( function do_something_serverside )
  • and the including of javascript file required ( if you’d like to know abit depth on ajax forms in WordPress see my post on that )
$greenShortyExample = new GreenShortyExample(); 

class GreenShortyExample {


    public function __construct() {

        $this->attach_actions();

        $this->attach_shortcodes();
    }

    function attach_actions() {



        add_action('wp_ajax_nopriv_green_do_something', array($this, 'do_something_serverside'));
        add_action('wp_ajax_green_do_something', array($this, 'do_something_serverside')); /* notice green_do_something appended to action name of wp_ajax_ */


        add_action('wp_enqueue_scripts', array($this, 'theme_enqueue_styles'), 99999);
    }

    function theme_enqueue_styles() {

        /*
         * include the js
         */

        wp_enqueue_script('green-script', plugin_dir_url(__FILE__) . '../js/ajax_call_to_handle_form_submit.js', array('jquery'));

        // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
        wp_localize_script('green-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'), 'we_value' => 1234));
    }

    function do_something_serverside() {
        
        echo "true";  // output to ajax call        
        die();
       
    }


    function attach_shortcodes() {


        add_shortcode('shortcode_with_form', array($this, 'shortcode_with_form_code'));
    }

    function shortcode_with_form_code($atts, $content = null) {

        if ($this->formOk()) {
            return " <div>thanks your form has been submitted</div>";
        } else {
            return $this->show_form();
        }
    }

    function show_form() {

        $form = '
            
       
        <form id="green_form" action="">
        

          
          field1:<br>
          
          <input type="text" name="field1" value="">
          <br>
          
          field2:<br>
          
          <input type="text" name="field2" value="">
          <br>
          
          <br>
          <input type="submit" value="Submit" >
          
        </form> 
        
      


';

        return $form;
    }

    
    function formOk(){
        
        
        return true; // use session or something to check
        
    }
}

 

Hope you find this interesting if you’re looking to add a form to a shortcode.

 

 

 

Leave a Comment