How to create a mail counter for Contact Form 7

Learn how to implement a simple sent mail counter for your contact form using shortcodes and action hooks.

Written by

Chris Mavricos

Published on

BlogWordPress Tutorials

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).

//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]

Some Notes

  • The counter only increments when the mail is actually sent. Form loads and failed sends won’t trigger the count to increase.
  • If two contact forms are submitted without reloading the page, the count will be incremented properly, but it won’t be reflected in the email. This is because the count that is sent in the email is only updated when the page loads. To update it without a page load, you’d need to write some JS that hooks into CF7’s send callbacks.

That’s about it – enjoy! Let me know in the comments if you find this useful (or run into any trouble).

Chris Mavricos

Hi, I'm Chris. I'm a web developer and founder of SevenSpark located in Boulder, CO. I've been developing websites since 2004, and have extensive experience in WordPress theme, plugin, and custom development over the last 15+ years.