Reputation: 3543
Case: I have a form in the page which enables users to add certain values in a simple text file. Now I want to redirect to the same page after values have been added successfully.
The read/write code all works great, I even put redirection code but this would display warning that header information is already sent
.
Headers I tried:
header("Location: some_url_here_in_same_site");
wp_redirect("some_url_here_in_same_site");
My Form code:
if(isset($_POST['txtName'])}
// form validation code here
if(successful)
wp_redirect("some_url_here_in_same_site");
}
PROBLEM:
ob_start
wonb't work, so don't suggest me this eitherUpvotes: 2
Views: 5536
Reputation: 3543
Ok I managed to do it using Hooks. I did redirection using the code below. Note that the form action is set to admin-post.php
<form action="admin-post.php" name="frmHardware" id="frmHardware" method="post">
<!-- form elements -->
<!-- Essential field for hook -->
<input type="hidden" name="action" value="save_hw" />
</form>
Then in my plugin's main file, I added the following:
add_action('admin_init', 'RAGLD_dashboard_hardware_init' ); // action hook add/remove hardware
Where, the function definition is as follows:
Also note that the first argument is derived from admin_post
which is a reserved word is combined with the action
hidden field in the form above.
function RAGLD_dashboard_hardware_init() {
// checking for form submission when new hardware is added
add_action( 'admin_post_save_hw', 'RAGLD_process_hw_form' );
}
after the evaluation that form has been submitted in above add_action
, function RAGLD_process_hw_form
will be called which is meant to validate form entries and take actions/redirections accordingly.
function RAGLD_process_hw_form() {
if (form_is_validated) {
wp_redirect( add_query_arg( array('page' => 'ragld/edit-hardware', 'action'=> 'InvalidData'), admin_url() ));
} else {
//do something else
}
}
This is the solution I could think of for the time being, you can suggest your answers if you feel they are more effective.
Upvotes: 7