Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Add Alphanumeric Format of Custom Order Numbers in WooCommerce?

By default, WooCommerce assigns numerical order numbers to transactions, starting from 1 and incrementing with each new order. But if you run a big store, you might want complex order numbers that are harder to guess for security reasons. This post will show you how to create a unique alphanumeric string for each order, combining letters and numbers in a random sequence.

Solution: Add Alphanumeric Format of Custom Order Numbers

The code snippet modifies the default WooCommerce order IDs with unique custom order numbers generated in alphanumeric formats.

add_filter( 'woocommerce_checkout_create_order', 'ts_save_order_number_metadata' );

function ts_save_order_number_metadata( $order ) {
    // Define the number of desired digits for the numeric part
    $digits = 4;

    // Define the letters for the alphabetic part
    $letters = range('A', 'Z');

    // Get the current sequential counter for the numeric part
    $data = get_option( 'wc_sequential_order_number' );
    $number = isset( $data['sequential'] ) ? intval( $data['sequential'] ) + 1 : 1;
    $data['sequential'] = $number;

    // Update the sequential counter
    update_option( 'wc_sequential_order_number', $data );

    // Calculate the alphabetic part of the order number
    $alphabetic_index = ($number - 1) % count($letters); // Subtract 1 to start from 'A'
    $alphabetic_part = $letters[$alphabetic_index];

    // Combine the alphabetic and numeric parts
    $order_number = $alphabetic_part . str_pad( $number, $digits, '0', STR_PAD_LEFT );

    // Add the order number as custom metadata
    $order->add_meta_data( '_order_number', $order_number, true );
}

// Add filter to read the order number from metadata
add_filter( 'woocommerce_order_number', 'ts_define_order_number', 10, 2 );

function ts_define_order_number( $order_id, $order ) {
    // Read the order number from metadata
    if ( $order_number = $order->get_meta( '_order_number' ) ) {
        $order_id = $order_number;
    }
    return $order_id;
}

Output

When a new order is created in WooCommerce, instead of the default numerical order numbers, this code will generate custom alphanumeric order numbers.

How to Add Alphanumeric Format of Custom Order Numbers in WooCommerce? - Tyche Softwares

There’s so much you can do to add additional features and functionalities tailored to the WooCommerce order numbering system. For instance, you can combine multiple elements such as product categories and timestamps, and append them to custom order numbers, making the order IDs informative and unique.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
0 Comments
Newest
Oldest
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x