How to Increment a Count on Each Form Submission

Introduction

Would you like to increment a count on each form submission inside a Hidden Field? You can easily stamp each entry with an increment count to track of the number of entries in order on each entry. In this tutorial, we’ll start by adding a Hidden Field to your form that will store the count and then a small PHP snippet that will create the count for you.

Creating the form

To begin, we’ll create a new form. Add all the relevant field to your form and then before you save the form, be sure to add a Hidden Field. This field will store the number as each entry is submitted.

Add a hidden field to your form

Adding the snippet to increment a count

Next, you’ll need to add the code snippet that will assign the count to each form submission.

If you need help in adding code snippets to your site, pleasereview this tutorial.

/**
 * Increment total entry number on each submission
 *
 * @link https://wpforms.com/developers/how-to-increment-a-count-on-each-form-submission
 * 
 */

function wpf_dev_update_total_field( $fields, $entry, $form_data ) {

	// Only run on my form with ID = 817
	if( $form_data[ 'id' ] != 817 ) {
		return $fields;
	}

	// Count the entries so far and increment the hidden field count by 1 on each submit
	$fields[4]['value'] = wpforms()->entry->get_entries( array( 'form_id' => 817 ), true ) + 1;

	return $fields;
}
add_filter( 'wpforms_process_filter', 'wpf_dev_update_total_field', 10, 3 );

The snippet will only run on the form ID 817. You’ll need to update this number to match your own form ID. The $fields[4] will need to be updated to match the field ID you have for the Hidden Field.

If you need any assistance finding your form ID and field ID, please check out this tutorial.

As each form submission is entered, the count increments by one that you see in the snippet with + 1.

It’s important to note that if for any reason, you would delete a form entry, this will throw off your count and could cause duplicate numbers on your count.

Each entry will now increment the number by one inside the hidden field

And that’s all you need to increment a count on each form entry. Would you like to find out other ways in which you can use the Hidden Field? Such as assigning a unique ID number on each submission? Take a look at our article on How to Create a Unique ID for Each Form Entry.

Filter Reference: wpforms_process_filter