I’m trying to assign every new order to a list of shop managers. What I need is like a queue, so every time a new order is created assign to the next shop manager in the queue.
This is the code I have:
function before_checkout_create_order($order, $data) { global $i; switch ($i) { case 0: $user = get_user_by('email', 'firstShopManagere@example.com'); break; case 1: $user = get_user_by('email', 'secondShopManager@example.com'); $i=0; break; } $userLastName = $user->user_lastname; $order->update_meta_data('asesor_asignado',$userLastName); $i++; } add_action('woocommerce_checkout_create_order', 'before_checkout_create_order', 20, 2);
The problem I’m dealing with now is that the $i
variable can’t be stored even though I increment the value that doesn’t change so that the next time the value is 0 again. Also every time $i
reaches 4, it should go back to 0
Any advice?
Advertisement
Answer
To manage $i
you can use the following WordPress functions:
- add_option() – Adds a new option
- update_option() – Updates the value of an option that was already added
- get_option() – Retrieves an option value based on an option name
These will allow you to modify or reset $i
every time the hook callback function is called
So you get:
function action_woocommerce_checkout_create_order( $order, $data ) { // Initialize $i = 0; $user = ''; // Option does not exist if ( ! get_option( 'my_counter') ) { // Adds a new option add_option( 'my_counter', $i ); } else { // Get value $i = get_option( 'my_counter' ); } // Compare switch ( $i ) { case 0: $user_name = 'user_0'; break; case 1: $user_name = 'user_1'; break; case 2: $user_name = 'user_2'; break; case 3: $user_name = 'user_3'; break; case 4: $user_name = 'user_4'; break; } // Update meta data $order->update_meta_data( 'asesor_asignado', $user_name ); // $i less than if ( $i < 4 ) { // increment $i++; } else { // Reset $i = 0; } // Updates the value of an option that was already added update_option( 'my_counter', $i ); } add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );