I cannot get set_price() to work no matter what I do. To override prices in woocommerce I've noted answers from as recently as 2021 that indicate that you must:
- Use woocommerce_before_calculate_totals hook instead.
- Use WC_Cart get_cart() method instead
- Use WC_product set_price() method instead
Change cart item prices in Woocommerce 3
However, for me, running WC 6.3.1, using the woocommerce_before_calculate_totals hook means it never seems to run at all with any priority from 10 to 9999 (instead of the woocommerce_before_add_to_cart_form hook, which does appear to run).
All of the code snippets I have seen and tried use some version of this loop. If I can get to the function (using woocommerce_before_add_to_cart_form, because woocommerce_before_calculate_totals seems not to run), the $cart object is present, the loop iterates and the get_price() method works.
However, the WC set_price method does not seem to work and the price does not change in the cart. I've seen some note that it works with literal numbers as arguments but not with variables. For me it fails in every form.
I've seen others post this question as well, but I have not seen any recent answers that work. I have also noted some references to session variables being needed to make this work, without explanation of how it would apply to this code.
foreach ( $cart as $cart_item_key => $cart_item ) {
//Some use $product as the object
$product = $cart_item['data'];
$price = $product->get_price();
$custom_price = $price * 1.1;
$product->set_price($custom_price);
//Some use $cart_item['data'] directly,
$custom_price = 10;
$cart_item['data']->set_price($custom_price);
//Some get fancy with looking for the method
if( method_exists( $product, 'set_price' ) )
$product->set_price( $custom_price );
else
$product->price = $custom_price;
}