1

I need to change the Woocommerce order number from 4 to 5 digits. I know I can a prefix or suffix with this

add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number', 1, 2);

function change_woocommerce_order_number( $order_id, $order ) {
    $prefix = 'WC';
    $suffix = '-XY'; 
    return $prefix . $order->id . $suffix;
}

But how can I change the number of digits?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
flor48
  • 89
  • 7

1 Answers1

4

Use str_pad() PHP function as follows:

add_filter( 'woocommerce_order_number', 'customize_order_number', 10, 2 );
function customize_order_number( $order_id, $order ) {
    $digits = 5;
    $prefix = '';
    $suffix = ''; 

    return $prefix . str_pad($order_id, $digits, '0', STR_PAD_LEFT) . $suffix;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related: Formatting a number with leading zeros in PHP

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • This works well and does exactly what I want. – flor48 Feb 20 '21 at 06:57
  • @LoicTheAztec Does this mean that order numbers will go from 00001 to 99999 or from 00001 to 0000099999? Meaning; are we extending the order number length or just adding 0:s in front of it? Thanks for helping me understand. –  Feb 20 '21 at 08:25