RadicalM1nd
RadicalM1nd

Reputation: 147

Do something for each order item based on quantity purchased in WooCommerce

I am using PHP Post to create an account with a different API for each product that the user purchased.

My current code looks like this:

add_action( 'woocommerce_thankyou', 'create_account' );
function create_account( $order_id ){
 $order = wc_get_order( $order_id );
 $items = $order->get_items(); 
 foreach ( $items as $item_id => $item ) {
   $product_id = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();
   if ( $product_id === xxx) {
       //do something
   }
   if ( $product_id === yyy) {
       //do something else
   }
}

Now if product xxx and yyy are purchased, the function loops through them correctly and creates 2 accounts.

However here's my issue:
Right now it only creates one account for xxx and one for yyy, no matter the amount purchased.
If I purchase "xxx" 5 times (quantity 5) and "yyy" 3 times (quantity 3), I want 8 (5 + 3) individual accounts to be created. I thought the foreach loop would do this, but it doesn't seems to consider the order item quantity.

How can I handle order Item quantity and do something for each product unit?

Upvotes: 0

Views: 158

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

Use a FOR loop based on order item quantity to handle an event based on quantity this way:

add_action( 'woocommerce_thankyou', 'create_account' );
function create_account( $order_id ){
    $order = wc_get_order( $order_id );

    foreach ( $order->get_items() as $item ) {
        $product_ids = array($item->get_product_id(), $item->get_variation_id());
        
        $product_id1 = 153; // <== Here define the 'xxx' product id
        $product_id2 = 228; // <== Here define the 'yyy' product id
        
        $quantity = $item->get_quantity();
        
        if ( in_array( $product_id1, $product_ids ) ) {
            for ( $i = 1; $i <= $quantity; $i++ ) {
                // do something
            }
        } 
        elseif ( in_array( $product_id2, $product_ids ) ) {
            for ( $i = 1; $i <= $quantity; $i++ ) {
                // do something else
            }
        }
    }
}

It should works.

Upvotes: 2

Related Questions