I would like to know how can I add a unique random number to my WooCommerce orders which are visible to the customer and at WooCommerce orders.
For example, When there is a new order. It will have it's usual order ID and an additional reference ID. This reference number has to be unique for each order. So that, can be used as a way to identify each order.
Thanks in advance :)
The basic idea is to generate a random number and add it as order meta. This would something like the following. This mayn't be the perfect one, but will lead you to it.
function create_reference_id( $order, $data ){
$random = write_function_for_random_id(); //Write the function to create random ID
$order->update_meta_data( 'custom_id', $random ); // replace custom_id with your meta key name.
}
add_action('woocommerce_checkout_create_order', 'create_reference_id', 10, 2);
This will add ID to WooCommerce Order object. Then you need to write code to show ID in email.
UPDATE
For the random number function you can use combination of order id and the value returned from wp_rand()
function.
If that's the case then you need to write as following.
function create_order_reference_id( $order_id, $data ){
$random = $order_id.'_'.wp_rand(1, 1000);
$order = wc_get_order( $order_id );
$order->update_meta_data( 'custom_id', $random );
$order->save();
}
add_action('woocommerce_checkout_update_order_meta', 'create_order_reference_id', 10, 2);