I have a custom form which posts data to wpdb
.
Currently, after form submit, my form keeps the user on the same page, but I'd like to redirect them to a thank you page.
Here is how the form is set up currently:
<form action="<?php echo esc_url( get_the_permalink() ); ?>?ref=<?php echo $reference; ?>" method="post">
// fields
</form>
Note: $reference
is getting a query string from the URL.
I am then getting the data and posting it to wpdb
:
if(isset($_POST['submit'])){
insert_row();
}
function insert_row(){
global $wpdb;
$rsvp_table = $wpdb->prefix . 'rsvp';
// get and sanitize fields
$fullname = sanitize_text_field( $_POST['full_name']);
if ( ! wp_verify_nonce( $_POST['rsvp_nonce'], 'rsvp_nonce' ) ) {
return; // Nonce verification failed, do not insert data
} else {
$wpdb->insert($rsvp_table,
array(
'fullname' => $fullname,
),
array(
'%s', // fullname
)
);
}
if ( $wpdb->last_error !== '' ) {
echo $wpdb->last_error; // There was an error
} else {
echo 'Data was inserted successfully'; // Success
}
}
Then, in functions.php
, I have the following:
add_action('init', 'redirectAfterSubmit');
function redirectAfterSubmit() {
if (isset($_POST["submit"])) {
wp_redirect( "/thank-you", 301 );
die();
}
}
}
Now, on form submit, this does redirect me to the thank you page, but it doesn't post the data to the database. The redirect is happening before posting the data it seems?
Edit
My form markup and database insertion (inc form handling) is in a component called rsvp.php
which is included on a custom template called homepage
:
<?php
/* Template Name: Homepage */
get_header();
get_template_part('templates/components/rsvp');
get_footer();
?>
Edit 2
Handle insertion of row before redirect in functions.php
add_action('init', 'redirectAfterSubmit');
function redirectAfterSubmit() {
if (isset($_POST["submit"])) {
insert_row();
wp_redirect( "/thank-you", 301 );
die();
}
}
function insert_row(){
// form handing here
}