Contact Form 7 is probably the most used plugin considering that WordPress official stats rank it 2nd after Akismet which comes bundled with WordPress.
I myself use it a lot, and I had the chance to extend it in different ways depending on my current client needs. The last challenge I had was to add code that runs when the on_sent_ok
event is triggered, my client wanted me to add the additional code inside the plugin, so that people won’t be able to remove that code unless they deactivate the plugin.
long story short this is how to do it:
Hook to wpcf7_contact_form_properties
This filter hook allows you to modify the WPCF7 form properties, I’m specially interested in “Additional Settings“, let us first hook our callback to the Contact Form 7 filter hook:
add_filter( 'wpcf7_contact_form_properties', 'my_plugin_wpcf7_properties' , 10, 2 );
Now let’s write the callback function my_plugin_wpcf7_properties()
, one thing to note here is that Contact Form 7 expects additional settings to be entered in a special format, this one:
event_A: "Code to run for event_A" event_B: "Code to run for event_B" event_B: "Another Code to run for event_B"
Write the callback function that injects additional settigns
Empty lines are fine, so to be on the safe side, I will add a couple of new lines, one before and one after the additional setting, here’s the code:
/**
* Add the code that will run when on_sent_ok is triggered;
*/
function my_plugin_wpcf7_properties( $properties, $contact_form_obj /* unused */ ){
$properties[ 'additional_settings' ] .=
"\n"
. 'on_sent_ok: "console.log(1);"' . "\n"
// . 'on_sent_ok: "console.log(2);"' . "\n"
// . 'on_sent_ok: "console.log(3);"' . "\n"
;
return $properties;
}
The nice thing here is that you can add as many on_sent_ok
(or others) as you want as long as you separate them with new lines.
Leave a Reply