Search code examples
wordpressrandomwoocommerceorders

Generate a random order number but prevent regeneration in WooCommerce


I am trying to add a random string when the order number is created as the default sequential number can be very easily guessed.

I tried this snippet:

function generate_random_string( $length = 16 ) {
    return substr( str_shuffle( str_repeat( $x = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil( $length / strlen( $x ) ) ) ), 1, $length );
}
    
add_filter( 'woocommerce_order_number', 'ct_change_woocommerce_order_number', 1, 2);

function ct_change_woocommerce_order_number( $order_id, $order ) {
     $random_string1 = generate_random_string(5);
    return $random_string1 . $order->get_id();
}

The problem is that this change the order number every time the order number is requested somewhere.

This would work if I will use a constant prefix and suffix, but in the actual way a different order number is shown each time for the same order. Any advice?


Solution

  • To prevent this you can save the result as meta data, once this exists return the meta data instead of the result of the function

    So you get:

    function generate_random_string( $length = 16 ) {
        return substr( str_shuffle( str_repeat( $x = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil( $length / strlen( $x ) ) ) ), 1, $length );
    }
    
    function filter_woocommerce_order_number( $order_number, $order ) {
        // Get meta
        $random_meta_string = $order->get_meta( '_random_meta_string' );
    
        // When meta empty
        if ( empty ( $random_meta_string ) ) {
            // Call function
            $generate_random_string = generate_random_string( 5 );
    
            // Append
            $random_string = $generate_random_string . $order->get_id();
    
            // Add the meta data
            $order->update_meta_data( '_random_meta_string', $random_string );
    
            // Return random string
            $order_number = $random_string;
        } else {
            // Return meta
            $order_number = $random_meta_string;
        }
        
        return $order_number;
    }
    add_filter( 'woocommerce_order_number', 'filter_woocommerce_order_number', 10, 2 );