How to Overwrite Entries From Users Who Have Already Submitted a Form

Overview

Would you like to overwrite entries from users who have already submitted a form? In some cases you wish to overwrite entries so that the user can only submit one entry on each form. With a small PHP snippet you can allow this on your site for just one single form or even for all forms.

Setup

By default, unless you are using the Form Locker addon, all users can submit as many entries as they wish to all of your forms.

Users can submit as many entries as they can based on your form settings

Using this snippet below, this code will look for any previous entries on this form from the user ID and overwrite their entries with the latest entry so each of your members will only have one form entry for each form you’ve created.

If you need any help on adding code snippets to your site, please review this tutorial.

/*
 * Remove all user entries before saving the entry - this is for all forms.
 *
 * @link https://wpforms.com/developers/how-to-overwrite-entries-from-users-who-have-already-submitted-a-form/
 *
 */

function remove_all_before_entry_save( $fields, $entry, $form_id ) {

        //get the current user's user ID
	$user_id = get_current_user_id();

        //check if the user is logged in, if not logged in skip this code snippet all together
	if ( empty( $user_id ) ) {
		return;
	}

        //perform a query for any entries submitted on this form by this user ID
	$entries = wpforms()->entry->get_entries(
		[
			'form_id' => $form_id,
			'user_id' => $user_id,
			'number'  => -1,
			'select'  => 'entry_ids',
			'cap'     => false,
		]
	);

        //for any previous entries this user has submitted on this form, remove them and replace them with this entry only 
	foreach ( $entries as $_entry ) {
		wpforms()->entry->delete( $_entry->entry_id, [ 'cap' => false ] );
	}
}
add_action( 'wpforms_process_entry_save', 'remove_all_before_entry_save', 9, 3 );

It’s important to note that if the user isn’t logged in, this code snippet will not run. This code snippet can only run if a user is logged in at the time of submitting any form entries.

When this user submits a new entry, that entry will overwrite all previous entries on this form.

using this code snippet you can now overwrite entries previously submitted by the same user

And that’s all you need! Would you like to learn how to display a message to your visitors if they are already logged in? Take a look at our tutorial on How to Display a Message When the User is Already Logged In.

Action Reference: wpforms_process_entry_save