Contact Form 7 Tips – Custom Functions

1. How to remove Contact Form 7 auto added p tags?

Remove wpautop in contact form 7  by filter method. It is good method is add following code in selected theme functions.php 

add_filter('wpcf7_autop_or_not', '__return_false');

Alternative method :-

We can disable wpautop for the cf7 by placing the following constant in wp-config.php

define( 'WPCF7_AUTOP', false );

2. How to add a custom function on email send?

We can access javascript events as follows

$(document).on('spam.wpcf7', function () {
    console.log('submit.wpcf7 was triggered!');
});

$(document).on('invalid.wpcf7', function () {
    console.log('invalid.wpcf7 was triggered!');
});

$(document).on('mailsent.wpcf7', function () {
    console.log('mailsent.wpcf7 was triggered!');
});


$(document).on('mailfailed.wpcf7', function () {
    console.log('mailfailed.wpcf7 was triggered!');
});

In php, We can access send data by wpcf7_before_send_mail 

Check sample code:-

add_action( 'wpcf7_before_send_mail', 'process_contact_form_data' );
function process_contact_form_data( $contact_data ){

    var_dump($contact_data->posted_data);
            $name = $contact_data->posted_data["your-name"];
    $email = $contact_data->posted_data["your-email"];

    echo $name ;
    echo $email;                
}

for testing you can try as follows:-

add_action( 'wpcf7_before_send_mail', 'process_contact_form_data' );
function process_contact_form_data( $contact_data ){
    ob_start();
    var_dump($contact_data->posted_data);
            $name = $contact_data->posted_data["your-name"];
    $email = $contact_data->posted_data["your-email"];

    echo $name ;
    echo $email;   
    $h = fopen('testdata.html','a');  
    fwrite($h, ob_get_clean());
    fclose($h);  
}

We can analyze data from testdata.html file in root folder.

3. Contact Form 7 AJAX Callback

document.addEventListener( 'wpcf7mailsent', function( event ) {
  alert( "Fire!" );
}, false );
  • wpcf7invalid — Fires when an Ajax form submission has completed successfully, but mail hasn’t been sent because there are fields with invalid input.
  • wpcf7spam — Fires when an Ajax form submission has completed successfully, but mail hasn’t been sent because a possible spam activity has been detected.
  • wpcf7mailsent — Fires when an Ajax form submission has completed successfully, and mail has been sent.
  • wpcf7mailfailed — Fires when an Ajax form submission has completed successfully, but it has failed in sending mail.
  • wpcf7submit — Fires when an Ajax form submission has completed successfully, regardless of other incidents.