Wordpress - Contact Form 7 - Execute code AFTER mail send
For anybody still landing here looking for a way to run some PHP code after the email has been sent, Contact Form 7 has a wpcf7_mail_sent
hook for exactly this. Usage looks a little like:
// ...in functions.php
add_action('wpcf7_mail_sent', function ($cf7) {
// Run code after the email has been sent
});
There is also wpcf7_mail_failed
, which lets you hook into when the email fails.
EDIT:
Please note that as of 2017 'on_sent_ok' is deprecated. This means that your code will stop working at some point in the future (likely by the end of 2017). The recommended solution is using DOM event listeners directly. For example, if you used:
on_sent_ok: "ga( 'send', 'event', 'Contact Form', 'submit' );"
You should replace it with:
document.addEventListener( 'wpcf7mailsent', function( event ) {
ga( 'send', 'event', 'Contact Form', 'submit' );
}, false );
The JavaScript code can be placed e.g. in the footer of your page.
ORIGINAL ANSWER:
Ok figured it out. In the specific form settings, go to the additional fields tab. Type in the following:
on_sent_ok: "location.replace('http://www.website-redirect.com');"
It's working like a charm for me now. Hope this helps other developers in the future as well.
I know the image is in Dutch ... but you can't miss it with the big red lines around the tab name.
Using on_sent_ok as explained at contactform7.com/additional-settings can be very useful for adding some simple JavaScript like redirecting to another page.
However it is rather prone to failing due to Javascript conflicts with either your current WordPress theme or one of the other plugins you are using.
on_sent_ok is the absolutely last thing that runs in Contact Form 7, so any interferring Javascript Conflict can stop this completing.
As an alternative, Contact Form 7 has a large number of hooks which are listed at http://hookr.io/plugins/contact-form-7/. These can provide a better targeted, more robust solution.