I’ve trying to write my campaign plugin.
Here is the problem,
I want to update, line_subtotal
and line_total
in a product in $cart_items
.
1- woocommerce_cart_product_subtotal
is not really working.
2- I tried to redefine array’s element by cart_item_key
foreach($cartItems as $hash => $perProduct)
{
if($perProduct['product_id'] = $lastItemsProductId)
{
if($lastItemsQuantity > 1)
{
$lineSubtotal = data_get($lastItemInCart, 'line_subtotal');
$lineTotal = data_get($lastItemInCart, 'line_total');
$newQuantity = $lastItemsQuantity-1;
$lastItemInCart['line_subtotal'] = $newQuantity * $lastItemsPrice;
$lastItemInCart['line_total'] = $newQuantity * $lastItemsPrice;
$cartItems[$lastItemsKey] = $lastItemInCart;
WC()->cart->calculate_totals();
} else {
}
}
}
Also this function runs, in woocommerce_before_calculate_totals
action.
When i try it, with woocommerce_get_cart_contents
filter, my cart empty itself .
3- The scenario :
When i add A product, (if is selected by system) and if quantity is more than 2, i want to make discount about this product.
Any helps ? Thanks.
Here is the answer
/**
* Add filter for order list
*
* @param [int] $product_subtotal
* @param [object] $product
* @param [int] $quantity
* @param [array] $cart
* @return void
*/
public function filterWoocommerceCartProductSubtotal($product_subtotal, $product, $quantity, $cart) : string
{
$appliedCoupons = $cart ? $cart->get_applied_coupons() : null;
$cartCount = $cart ? count($cart->get_cart()) : 0;
$cartItems = $cart->get_cart();
$lastItemInCart = last($cartItems);
$lastItemsProductId = data_get($lastItemInCart, 'product_id', data_get($lastItemInCart, 'product_id'));
$lastItemsPrice = $lastItemInCart['data']->get_regular_price();
$lastItemsQuantity = data_get($lastItemInCart, 'quantity');
$lastItemsKey = data_get($lastItemInCart, 'key');
if( in_array('3al2ode', $appliedCoupons)){
if($lastItemsQuantity > 1) {
if(@data_get($product,'id') == $lastItemsProductId)
{
$newSubTotal = 0;
$price = $product->get_price();
$newQuantity = $lastItemsQuantity-1;
$quantity = $newQuantity;
$newSubTotal += $price * $quantity;
return $newSubTotal ? wc_price($newSubTotal) : $product_subtotal;
}
}
}
return $product_subtotal;
}
The right, filter should be like;
add_filter( 'woocommerce_cart_product_subtotal', [$this,'filterWoocommerceCartProductSubtotal'], 10, 4);
2
Answers
The right, filter should be like;
add_filter( 'woocommerce_cart_product_subtotal', [$this,'filterWoocommerceCartProductSubtotal'], 10, 4);
As per your current scenario – When I add A product, (it is selected by the system) and if the quantity is more than 2, I want to make a discount on this product.
You should try this-
You can update/modify condition accordingly.