I have a form on my wordpress site. On form submission I want to:
1) Capture the form data
2) Run database queries using these data
3) Process the results and use these to construct a query string
4) Redirect user to site root + query string
Outside WordPress, I'd solve this by making the form action="my_query_string_constructor.php"
and just do all the necessary processing of the post data there. I considered doing something analogous in WordPress by making the form action some like "single-my_query_string_constructor_posts.php"
but this feels very hacky and I'd much rather have a solution which fits with best practice.
I want to make sure that my solution is secure but I'm not sure about the best way to use the nonce system here. I'm also unsure whether I should put my database queries and query string construction code in the page itself, or in functions.php, or indeed somewhere else.
Would really appreciate your advice on the best approach to take (I'm not asking you to write the code for me!)
Your best bet is creating a simple plugin to handle processing the data (and ideally generating the form since then you can handle nonces easily).
I'll just cover what you need for the plugin to handle the saving of the form data and the redirect.
add_action( 'wp_ajax_saveYourForm', 'saveYourForm' );
add_action( 'wp_ajax_nopriv_saveYourForm', 'saveYourForm' );
function saveYourForm()
{
check_ajax_referer('yourFormNonce'); //comment this out if you're not using nonces
global $wpdb;
.... do your DB stuff here ....
wp_redirect(add_query_arg('arg',$_POST['forminput'],site_url('yourpage.php')));
}
Make sure your form posts to wp-admin/admin-ajax.php and has an action field set to "saveYourForm" to match what's in the first argument of the add_action calls.
check_ajax_referer checks the nonce on an ajax call.
wp_redirect would handle the redirect back to your site. add_query_arg takes either two strings or an array to handle the query arguments to pass, and the last argument is the URL to redirect to. add_query_arg codex page
site_url redirects them to your main site URL, and passing 'yourpage.php' into it would send them to yoursite.com/yourpage.php.
Assuming $_POST['forminput'] was "blue", they would be redirects to http://yoursite.com/yourpage.php?arg=blue.