Wooommerce change item price in cart conditionally
asked 8 hours ago by @qa-2yintjdlmeu0rvr9uvxi 0 rep · 49 views
I want to sell plugins.
There will be yearly (regular) and lifetime licenses.
I have already created products with regular prices.
Now I don't want to duplicate all products just to create lifetime prices (which is different than regular price).
If I use this hook I can change the price in the cart:
add_action( 'woocommerce_before_calculate_totals', 'ap_woocommerce_before_calculate_totals', 20, 4 );
function ap_woocommerce_before_calculate_totals( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
if ( isset( $cart_item['ap_lifetime_license'] ) ){
//here get new price
$new_price = ...
$cart_item['data']->set_price( $new_price );
}
}
}
Is this code enough to cover all cases where products might be added and removed from cart, set different quantities etc.?