/*
* Create a unique ID with a specific number of characters and assign it to each form submission.
*
* @link https://wpforms.com/developers/how-to-create-a-unique-id-for-each-form-entry/
*/
// Generate Unique ID Smart Tag for WPForms
function wpf_dev_register_smarttag( $tags ) {
// Key is the tag, item is the tag name.
$tags[ 'unique_id' ] = 'Unique ID';
return $tags;
}
add_filter( 'wpforms_smart_tags', 'wpf_dev_register_smarttag' );
// Generate Unique ID value
function wpf_dev_process_smarttag( $content, $tag, $form_data, $fields, $entry_id ) {
// Only run if it is our desired tag.
if ( 'unique_id' === $tag && !$entry_id ) {
// generate a hexadecimal string based on the time to ensure uniqueness
// reduce the string to 6 characters
$uuid = substr(md5(time()), 0, 6);
// Replace the tag with our Unique ID.
$content = str_replace( '{unique_id}', $uuid, $content );
} elseif ( 'unique_id' === $tag && $entry_id ) {
foreach ($form_data[ 'fields' ] as $field) {
if ( preg_match('/\b{unique_id}\b/', $field[ 'default_value' ]) ) {
$field_id = $field[ 'id' ];
break;
}
}
$content = str_replace( '{unique_id}', $fields[$field_id][ 'value' ], $content);
}
return $content;
}
add_filter( 'wpforms_smart_tag_process', 'wpf_dev_process_smarttag', 10, 5 );