1

All cart items are adding programmatically. I am trying to set a product cost based on various factors that change for each instance of an item added to the cart.

I discovered Price Resolvers and it seemed like it was working until I ended up adding 2 of the same "dynamically priced" items to my cart. Each was passed different prices and in my resolver I can see that the price is set correctly for each item. However, in the cart, they both have the same cost (the cost of the last item added to the cart).

My guess is that I can only set the price of an item per php session and not per cart item add. Is this correct? Is there some other way to dynamically set price of a product as it is added to a cart?

0

1 Answer 1

1

Eventually sorted this out on my own. Simple answer is NO, this is not the purpose of Price Resolvers. Price Resolvers can be used to "statically" set a price based on something which does not change during the php session - such as location, year, etc. But if you need to modify the price due to user input at the time; the correct solution is to set the Unit Price.

Before looking at Resolvers I already had this code:

  $order_item = OrderItem::create([
    'type' => $item_type,
    'purchased_entity' => $variation->id(),
    'quantity' => isset($options['qty']) ? $options['qty'] : 1,
    'unit_price' => $my_dynamic_price,
  ]);

and I have seen posts and had been given suggestions that this works. It does not. Setting the unit_price at the time of OrderItem::create has no impact on the item's price. The correct way to do this is with the setUnitPrice() method like this:

  $order_item = OrderItem::create([
    'type' => $item_type,
    'purchased_entity' => $variation->id(),
    'quantity' => isset($options['qty']) ? $options['qty'] : 1,
    'unit_price' => $variation->getPrice(),  // may be overwritten by $options['cost']
  ]);

  // If we are setting a custom cost, override unit_price now.
  if (isset($options['cost']) && $options['cost']) {
    $order_item->setUnitPrice($options['cost'], TRUE);;
  }
  $order_item->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.