Post submit using shortcode and init

I’m trying to find the best way to return errors to a page once a form submitted by using a shortcode.

I’m adding a function to init such as –

Read More
add_action( 'init', 'contact_form_process_post' );

function contact_form_process_post() {
    if( isset( $_POST['unique_hidden_field'] ) ) {
        // process $_POST data here

        $errors = new WP_Error();

        if( empty( $_POST['full_name'] ) ) {
            $errors->add( 'invalid', __( 'Full name cannot be empty' ) );
        }

        if( count( $errors->get_error_messages() ) == 0 ) {
            wp_redirect( 'some_url ');
            exit();
        } else {
            // Return errors here
        }
    }
}

This works fine if there’s no errors (i.e all fields are valid), but if some fields are empty it should return to the form with those errors. If they are valid it re-directs to a confirmation page.

The problem is returning the errors from init to the content/shortcode. I can do it the following ways –

  1. Redirect back to the page setting the errors in the URL (query vars)
  2. Globalize a variable for the errors and use this in the shortcode
  3. Filter the_content and add the errors
  4. Store the errors in a session

I’d rather the URL stays the same, so option one is out. Option two works but it feels slightly “dirty”, along with option 3 which isn’t great. Option 4 could work, though WordPress doesn’t use sessions.

This will be used for along with JS validation (or when JS is disabled).

Maybe I’m missing an obvious way to do this?

Any suggestions?

Thanks!

Related posts