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

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.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top