on_sent_ok is deprecated

The Additional Setting “on_sent_ok” is used to assign a JavaScript code that will be executed when a form submission completes and mail has been sent successfully. It is often used for the purpose of tracking form submissions with web analytics services or redirecting to another page after a form submission.

The “on_sent_ok” and its sibling setting “on_submit” are deprecated and scheduled to be abolished by the end of 2017. It’s not that using those settings is unsafe, but it’s possible that enabling them will increase risk in case there are vulnerabilities in this plugin or in other components of your site. It’s time to replace them with a safer alternative.

Update: on_sent_ok and on_submit have been officially removed from Contact Form 7 5.0.


The recommended alternative to on_sent_ok is using DOM events. Coding with DOM events has a number of advantages over using on_sent_ok. For the details of Contact Form 7’s custom DOM events, please refer to the documentation.

In the rest of this post, I’ll explain with some examples how you can replace your on_sent_ok settings.

Replacing on_sent_ok with DOM events

Suppose that you currently have the following line of settings in the Additional Settings tab:

on_sent_ok: "ga( 'send', 'event', 'Contact Form', 'submit' );"

This setting tells Contact Form 7 to run the ga() (Google Analytics tracker) function when a form submission completes and mail has been sent successfully.

To replace it with an alternative code using DOM events, first, find the file named “functions.php” in the directory of your active theme. Second, add the following code at the bottom of the functions.php file:

add_action( 'wp_footer', 'mycustom_wp_footer' );
 
function mycustom_wp_footer() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
    ga( 'send', 'event', 'Contact Form', 'submit' );
}, false );
</script>
<?php
}

Third, remove the “on_sent_ok” line from the Additional Settings tab and save the contact form.

That’s it.

Targeting a specific contact form

If you have several contact forms and want to run the function only for a specific contact form, check the ID of the contact form like the following:

add_action( 'wp_footer', 'mycustom_wp_footer' );
 
function mycustom_wp_footer() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
    if ( '123' == event.detail.contactFormId ) {
        ga( 'send', 'event', 'Contact Form', 'submit' );
    }
}, false );
</script>
<?php
}

In this case, the ga() function will be executed only if the ID of the contact form (event.detail.contactFormId) is “123”.

You can find the ID of a contact form by looking for the “id” attribute in the contact-form-7 shortcode. For example, if the shortcode looks like this:

[contact-form-7 id="1234" title="Contact form 1"]

The ID of this contact form is “1234”.