1

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 -

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!

  • This is really too broad for a complete answer but... (1) I see nothing wrong with #3 (2) WordPress doesn't use sessions but PHP is PHP. (3) If you were using a class you wouldn't have to globalize variables. (4) You may also be able to use static variables depending on context. Maybe, pick on and edit the question so we can proceed. – s_ha_dum Jan 20 '14 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.