Home / eCommerce / Unique Order ID
Duplicate Snippet

Embed Snippet on Your Site

Unique Order ID

Creates a unique order ID

Code Preview
php
<?php
/*
 * Create a unique_id Smart Tag 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 ) {
         
        // Replace the tag with our Unique ID that will be prefixed with wpf.
        $content = str_replace( '{unique_id}', uniqid( 'wpf', true ), $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 );

Comments

Add a Comment