I'm writing a plugin that uses a form to pass some data through to itself.

Is there any way to do this "The WordPress Way"?

Sample form code (on a custom submenu page added under "Tools"):

<form action="<?php echo get_admin_url() . 'admin-post.php'; ?>" method="post">
    <input name="some_input" type="text">
    <input name="other_input" type="text">

Then on the logic side of the plugin:

function my_process_form_data() {
    // Process the form data here and return the results
add_action( 'admin_post', 'my_process_form_data' );

Now that I've processed the form and have the resulting data (stored as a somewhat large array), what's the best way to return that data to the custom submenu page I've created?

I understand there are a few options:

  • Instead of posting to "admin-post.php", I could post directly to the page. But this makes for some messy code and conditionals (i.e. if results, load this, else, load this. Ideally the templating and the logic should be kept separate.
  • Use wp_redirect and store the data in the URL that it is redirecting to. But I have a large array of data to return to the end-user, so this isn't really an option.
  • Serialize the data and store temporarily in the database, through transients or options, unsetting the data in the db once the user has seen it. But this feels very 'hackish'.

Any suggestions how to get this large array of data back to my custom submenu page "the WordPress way"?

  • You can add custom action as admin_post_myaction and then add hidden field action=myaction to your form. Only problem is how to show the form again if there is an error (echoing just returns the content without the actual dashboard). – FrEaKmAn Jan 8 '15 at 14:12
  • 1
    See my answer using transients here: [1]: wordpress.stackexchange.com/a/203359/6593 – mos fetish Sep 22 '15 at 5:21
  • If you use a nonce you can call $_POST('_wp_http_referer') to get the form url, and then wp_safe_redirect and add_query_arg to return state and data. See my complete answer here wordpress.stackexchange.com/a/354269/84702 – juananruiz Dec 10 '19 at 8:35

The WordPress way of doing this is by not using the admin_post hook at all. Since this question was asked quiet a while ago I wonder if option was available back then.

Anyway you should create a custom settings page. Have a look at the complete example in the linked post. You will have to create a callback for each field.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.