Reputation: 25
In Cart, I added a button to create quotation orders. I am using a quantity range pricing plugin so all of my variable products have a wide range of pricing.
Eg. Product A's item cost is $5 when quantity is below 100. Item cost is $3 when quantity is 100 to 199.
My cart displays the correct item cost and I manage to retrieve each cart item's product price. However, I am unable to set the variation price and add the data into order.
Does anyone knows how can I solve this?
// Now we create the order
$order = wc_create_order();
// add products from cart to order
$items = WC()->cart->get_cart();
foreach($items as $item => $values) {
$_product = apply_filters( 'woocommerce_cart_item_product', $values['data'], $values, $item );
$tieredPrice = WC()->cart->get_product_price($_product);
$product_id = $values['product_id'];
$product = wc_get_product($product_id);
$quantity = (int)$values['quantity'];
$var_id = $values['variation_id'];
$variationsArray = array($values['variation']);
$var_product = new WC_Product_Variation($var_id);
$var_product->set_variation_price($tieredPrice); //how do I set variation price?
$order->add_product($var_product, $quantity, $variationsArray);
}
Thank you in advance.
Upvotes: 1
Views: 1795
Reputation: 253867
In cart $values['data']
is already an instance Of the WC_Product
object, so for a product variation it is directly an instance of the WC_Product_Variation
object, so this will be simple now.
The set_variation_price()
method doesn't exist for WC_Product objects, it is set_price()
…
So your revisited code will be:
// Now we create the order
$order = wc_create_order();
// Add products from cart to order
$cart = WC()->cart; // cart object
foreach( $cart->get_cart() as $cart_item_key => $cart_item) {
$product = $cart_item['data']; // An instance of the WC_Product object
$qty = intval($cart_item['quantity']); // The quantity
$tierced_price = $cart->get_product_price($_product); // your "tierced" price
$product->set_price( $tierced_price ); // <== <== <== <== <== <== SET THE PRICE
$args = array( $cart_item['variation'] ); // empty if not a variation
$order->add_product( $product, $qty, $args );
}
This should work
Upvotes: 1