2

Based on the trick of using set_query_var with get_template_part to easily pass variables from one template file to another (see here: Method 3), I thought I could use the same method for passing complex information back to a page after a form submission (error messages, next steps, topic URLs, etc.)

Very simply, I have an init hook listening for the form submission set up like this:

function vnmProcessForm() {
    if (isset($_POST['form-value'])) {

        $formVal = sanitize_title($_POST['form-value']);

        if ($formVal == 'all-done') {
            set_query_var('form-message', 'It looks like you are all done with this step! Now move on to <a href="/dashboard">setting up your dashboard</a>.');
        } else {
            set_query_var('form-message', 'Please complete all options in the form.');
        }

        // It's a lot more complex than this, but... MVC.
    }
}

add_action('init', 'vnmProcessForm');

My form action is the same URL that the form resides on (so, essentially, a refresh); however, when I try get_query_var('form-message') on that page, I get nothing. If I spit out all query_vars, form-message isn't among them.

I'm sort of perplexed as to why this would work seamlessly for something like get_template_part, yet fails to work in this instance. Is it something to do with the init hook being too early?

In the meantime I have 'solved' this by simply using $_POST instead of set_query_var, but I'm genuinely curious to know why that isn't working.

2
  • 1
    Query parsing happens much later than init, I'll guess that you can't set query vars until after the query is parsed, or at least they have to be among the list of known query vars for them to survive parsing.
    – Milo
    Commented Mar 12, 2017 at 15:42
  • @Milo That was my guess, but I couldn't find anything definitive (as in, to say that init was indeed far too early). I guess I'll just stick with $_POST for now, as it's working for me.
    – indextwo
    Commented Mar 12, 2017 at 20:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.