How to Redirect to a Dynamic URL after Contact Form 7 Submission [Ajax]

Few days back, I had a requirement where I had to redirect the user to some dynamic URL after the form is successfully submitted on Contact For 7 plugin.

As you will be knowing that you can redirect the user to some fixed URL by specifying on_sent_ok: http://example.com in the additional settings of your contact form. But you need to know the URL you want to redirect the user well in advance.

I did not know the URL in advance as it was going to be generated based on some condition after the form is submitted. Contact form 7 provides a hook named wpcf7_before_send_mail through which you can make some modifications or trigger some code before the contact form 7 mail is sent.

You might be thinking that the below code will work for redirect –

add_action( 'wpcf7_before_send_mail', 'my_custom_function' );
function my_custom_function(){
     wp_redirect( $my_dynamic_url );
}

But unfortunately, wp_redirect() will not work here as wpcf7_before_send_mail hook works on ajax ( as your contact form 7 is in ajax mode )

To make the redirection work in ajax mode, we need to set the on_sent_ok property through contact form 7 set_properties function. Check the below code –

add_action( 'wpcf7_before_send_mail', 'my_custom_function' );
function my_custom_function(){
        $permalink = 'http://example.com'; // Dynamic URL
        $wpcf7 = WPCF7_ContactForm::get_current();
	$wpcf7->set_properties(array(
		'additional_settings' => "on_sent_ok: \"location.replace('".$permalink."');\"",
	));
}

Once this hook is triggered, the user will be redirected to any URL that is stored in the $permalink variable.

3 Comments

  1. Giuseppe Rinella

    Great!

    But…how can i dynamic change $permalink variable?
    I have one form and after submit i must redirect to diffferent urls…how can i do this??

Leave a Reply

Your email address will not be published. Required fields are marked *