Advertisement
AndyScoffings

Generate Unique ID

Oct 17th, 2024
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | Source Code | 0 0
  1. /*
  2. * Create a unique ID with a specific number of characters and assign it to each form submission.
  3. *
  4. * @link https://wpforms.com/developers/how-to-create-a-unique-id-for-each-form-entry/
  5. */
  6.  
  7. // Generate Unique ID Smart Tag for WPForms
  8. function wpf_dev_register_smarttag( $tags ) {
  9.  
  10. // Key is the tag, item is the tag name.
  11. $tags[ 'unique_id' ] = 'Unique ID';
  12.  
  13. return $tags;
  14. }
  15.  
  16. /*
  17. * Generate Random 3char string
  18. */
  19. function randStr($chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', $length = 3) {
  20. return substr(str_shuffle($chars), 0, $length);
  21. }
  22.  
  23. /*
  24. * Generate random 3 digit number
  25. */
  26.  
  27. function randNum($chars = '0123456789', $length = 3) {
  28. return substr(str_shuffle($chars), 0, $length);
  29. }
  30.  
  31. /*
  32. * Generate Output
  33. */
  34.  
  35. function generateOutput() {
  36. $output = randStr() . randNum();
  37. return $output;
  38. }
  39.  
  40.  
  41. add_filter( 'wpforms_smart_tags', 'wpf_dev_register_smarttag' );
  42.  
  43. // Generate Unique ID value
  44. function wpf_dev_process_smarttag( $content, $tag, $form_data, $fields, $entry_id ) {
  45.  
  46. // Only run if it is our desired tag.
  47. if ( 'unique_id' === $tag && !$entry_id ) {
  48.  
  49. // generate a hexadecimal string based on the time to ensure uniqueness
  50. // reduce the string to 6 characters
  51. $uuid = randStr() . randNum();
  52.  
  53. // Replace the tag with our Unique ID.
  54. $content = str_replace( '{unique_id}', $uuid, $content );
  55. } elseif ( 'unique_id' === $tag && $entry_id ) {
  56.  
  57. foreach ($form_data[ 'fields' ] as $field) {
  58.  
  59. if ( preg_match('/\b{unique_id}\b/', $field[ 'default_value' ]) ) {
  60. $field_id = $field[ 'id' ];
  61. break;
  62. }
  63.  
  64. }
  65.  
  66. $content = str_replace( '{unique_id}', $fields[$field_id][ 'value' ], $content);
  67. }
  68.  
  69. return $content;
  70. }
  71.  
  72. add_filter( 'wpforms_smart_tag_process', 'wpf_dev_process_smarttag', 10, 5 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement