Multi step form, custom plugin

The process can be done by posting the form to the current page, and then using those values from the $_POST object to determine the next form.

In the simplest example, a hidden input named “page” can increase its value on each step. Set the value of additional hidden inputs with the data from $_POST if it is needed in later steps/forms.

The sample method below does this. I added a shortcode, [count_page_form] that can include it in a post or page so it’s easy to test. All of this would go in theme’s functions.php

(don’t use in production, obviously, no sanitization or validation being done here).

It should be enough of an example for you to modify what you have working.

Example:

add_shortcode('count_page_form','count_page_function');

function count_page_function(){
    global $wpdb;
    $current_page  =  $_SERVER['REQUEST_URI'];
    //check for $_POST value for our page_count, make it null if it isn't there since that means we're on page 1
    if ($_POST && $_POST['page']) { 
        $page_count   =   $_POST['page'];
    }
    else { 
        $page_count = null; 
    }
    //now let's start checking the page_count and displaying as needed
    if ( $page_count == NULL ) {
        echo '<form method="post" action="' . $current_page .'">
                <label for="first_name" id="first_name">First Name: </label>
                <input type="text" name="first_name" id="first_name" />

                <input type="hidden" value="1" name="page" />
                <input type="submit" />
            </form>';
            //the hidden input type above gives our $_POST['page'] a value of one upon submission
    }//end page 1
    elseif ( $page_count == 1 ) {
        //grab values from first $_POST, we will add them to hidden input below so new $_POST has them  
        $first_name =   $_POST['first_name'];

        echo '<h2>This is page two</h2>';
        // note below we add the hidden for first_name, and we change the value for page to 2
        echo '<form method="post" action="' . $current_page .'">
            <input type="hidden" name="first_name" id="first_name" value="'. $first_name .'" />
            <label for="second_name" id="second_name">Second Name: </label>
            <input type="text" name="second_name" id="second_name" />
            <input type="hidden" value="2" name="page" />
            <input type="submit" />
        </form>';

    }//end page 2
    elseif ($page_count == 2) {
        $first_name  = $_POST['first_name'];
        $second_name = $_POST['second_name'];

        echo '<h2>The third page!</h2>';
        echo $second_name;
        echo $first_name;
    }//end page 3
}//end count_page_function

Leave a Comment