Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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;
- }
- /*
- * Generate Random 3char string
- */
- function randStr($chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', $length = 3) {
- return substr(str_shuffle($chars), 0, $length);
- }
- /*
- * Generate random 3 digit number
- */
- function randNum($chars = '0123456789', $length = 3) {
- return substr(str_shuffle($chars), 0, $length);
- }
- /*
- * Generate Output
- */
- function generateOutput() {
- $output = randStr() . randNum();
- return $output;
- }
- 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 = randStr() . randNum();
- // 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 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement