Add assigned manager initials sequentially to WooCommerce order numbers

Viewed 204

With the following code I am able to add a prefix and a suffix to WooCommerce order number:

add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number' );
function change_woocommerce_order_number( $order_id ) {
    $prefix = 'VK/';
    $suffix = '/TS';
    $new_order_id = $prefix . $order_id . $suffix;

    return $new_order_id;
}

How we can prefix the order number with shop manager initials sequentially from an array of shop managers initials?

This way we can assign equally WooCommerce orders to each one of them.

Any help?
1 Answers

To have a prefixed order number with manager initials from an array of manager initials sequentially, use the following:

// Save prefixed order number as order meta data
add_action( 'woocommerce_checkout_update_order_meta', 'save_the_order_number', 10, 2 );
function save_the_order_number( $order_id, $data ) {
    // Here set the managers initials
    $initials = array('JKI', 'FGR', 'LFA', 'OPI', 'TME');
    
    $count    = count($initials); // Get the length of the array (manager initials count)
    $previous = get_option('last_assigned_manager'); // Load previous assigned manager initials value
    $prev_key = array_search($previous, $initials);  // Get the array key for previous manager initials value
    $now_key  = ($previous + 1) == $count ? 0 : $previous + 1; // Get the next array key (the current manager to be assigned)
    
    update_post_meta( $order_id, '_order_number', $initials[$now_key] . '-' . $order_id ); // Save prefixed order number 
    update_option( 'last_assigned_manager', $initials[$now_key] ); // Save current assigned manager initials value
}

// Assign order number meta data to get_orde_number method
add_filter( 'woocommerce_order_number', 'assign_order_number_from_meta_data', 10, 2 );
function assign_order_number_from_meta_data( $order_id, $order ) {
    // Get the order number (custom meta data)
    $order_number = $order->get_meta('_order_number'); 
    
    return $order_number ? $order_number : $order_id;
}

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

Related