Close

Counter on Contact Form 7

Here’s an easy way to set up a counter for your contact form using Contact Form 7 and Contact Form 7 Dynamic Text Extension. Basically, we’re setting up an action that will increment a counter each time an email is sent. We’re grabbing that count and placing it in the email using CF7 DTX.

Add the functional code

First, here’s the code to add (anywhere, but functions.php works well. It’ll be added to CF7 DTX some time down the road hopefully).

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
//Define the key to store in the database
define( 'CF7_COUNTER', 'cf7-counter' );
//Create the shortcode which will set the value for the DTX field
function cf7dtx_counter(){
    $val = get_option( CF7_COUNTER, 0) + 1;  //Increment the current count
    return $val;
}
add_shortcode('CF7_counter', 'cf7dtx_counter');
//Action performed when the mail is actually sent by CF7
function cf7dtx_increment_mail_counter(){
    $val = get_option( CF7_COUNTER, 0) + 1; //Increment the current count
    update_option(CF7_COUNTER, $val); //Update the settings with the new count
}
add_action('wpcf7_mail_sent', 'cf7dtx_increment_mail_counter');

Configure the Contact Form

Next, we set up our contact form. We’re going to add a new hidden dynamic field to it using CF7 DTX and the new shortcode we just wrote. Here’s what that code would look like in the Contact Form 7 Form Settings:

[dynamichidden cf7-counter "CF7_counter"]

Finally, we want to include the count in the message we receive, so we’ll add it to the CF7 Message Body field:

Count: [cf7-counter]

1
×
Hola, cómo podemos ayudarte.