1

I know in PHP I can just put action equal to random.php file and process the data there, but how in wordpress can I use already existing page with a custom template to submit a form to, so that after submitting a form on one page, user will be redirected to another page in wordpress with all his inputted credentials still available?

1
<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post">
<input type="hidden" name="action" value="your_action_name">

Add these in your form. Where admin-post.php will process your form. In that case based on the value of your_action_name that is provided by you, an action hook will get involved. Say for example if you add a hook like the following in functions.php of your theme or in your plugin

add_action( 'admin_post_nopriv_your_action_name', 'your_function_to_process_form' );

then for non logged in user

function your_function_to_process_form(){
// process your form here
}

will be called. From there you can process your form. For logged in user you need to rename your action to admin_post_your_action_name from admin_post_nopriv_your_action_name. Remember admin_post_ or admin_post_nopriv_ are available in admin-post.php to do_action appropriate action. Whatever you append at the end of admin_post_nopriv_ or admin_post_ will formulate a action hook. That needs to implemented by add_action(). If you pass contactform as a hidden action then your action hook will be either admin_post_nopriv_contactform or admin_post_contactform or both.

  • Wow, many steps. I understand everything in your explanation, except for one thing. So if say, after the form submission I want to take user to a new page with orher layout, how do I do that? Because like I said, in plain php I put another file name in action and just write html structure in that new file. Here you say put admin-post.php and specify hooks for functions.php. But where do I put a new page url with new html and styles for user to be redurected to? – Limpuls Nov 12 '18 at 23:26
  • you may use wp_redirect( 'your location' );. Put it at the end of your function after you have processed your form. – user119247 Nov 12 '18 at 23:29
  • Inside functions.php? – Limpuls Nov 12 '18 at 23:30
  • function your_function_to_process_form(){ //do processing your form then wp_redirect( 'your location' ); } – user119247 Nov 12 '18 at 23:31
  • Thanks. I just wonder why exactly it has to be done this way. Only submitting to admin-post.php. I wonder why to this and not something else. Is that just the way wordpress is and handles custom forms? Would love to read any resources on this if you have. – Limpuls Nov 12 '18 at 23:34

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.