Change subtotal after coupon discount applied Woocommerce
For my case i have cart.php woocommerce on custom template as bellow
<td class="product-subtotal" data-title="<?php esc_attr_e( 'Subtotal', 'woocommerce' ); ?>">
<?php
echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); // PHPCS: XSS ok.
?>
</td>
In my case i have a plan for change subtotal after coupon discount applied, and actually i have two method.
First i can calculate the discount directly on cart.php like bellow
<td class="product-subtotal" data-title="<?php esc_attr_e( 'Subtotal', 'woocommerce' ); ?>">
<?php
// Dapatkan subtotal produk tanpa diskon
$original_subtotal = $_product->get_price() * $cart_item['quantity'];
// Inisialisasi variabel diskon
$total_discount = 0;
// Loop melalui setiap kupon yang diterapkan
foreach ( WC()->cart->get_coupons() as $code => $coupon ) {
$coupon_amount = 0;
if ( in_array( $product_id, $coupon->get_product_ids() ) || empty( $coupon->get_product_ids() ) ) {
$discount_amount = WC()->cart->get_coupon_discount_amount( $code, WC()->cart->display_cart_ex_tax );
$coupon_amount += $discount_amount / count( WC()->cart->get_cart() );
}
$total_discount += $coupon_amount;
}
// Hitung subtotal baru dengan mengurangi total diskon
$new_subtotal = $original_subtotal - $total_discount;
// Pastikan subtotal baru tidak negatif
if ( $new_subtotal < 0 ) {
$new_subtotal = 0;
}
// Tampilkan subtotal baru
echo wc_price( $new_subtotal );
?>
</td>
But i think my first method makes my code looks untidy. So i have idea to replace wit funstions.php in my template
function custom_cart_item_subtotal( $subtotal, $cart_item, $cart_item_key ) {
$product = $cart_item['data'];
$quantity = $cart_item['quantity'];
$original_subtotal = $product->get_price() * $quantity;
// Initialize total discount
$total_discount = 0;
// Loop through applied coupons
foreach ( WC()->cart->get_applied_coupons() as $code ) {
$coupon = new WC_Coupon( $code ); // Instantiate WC_Coupon object for each applied coupon
// Check if the coupon is valid for this product or any product
if ( $coupon->is_valid_for_product( $product ) || $coupon->is_valid_for_product( 0 ) ) {
// Calculate discount amount for the specific cart item
$discount_amount = $coupon->get_discount_amount( $original_subtotal, $cart_item, WC()->cart->display_cart_ex_tax );
$total_discount += $discount_amount;
}
}
// Calculate new subtotal after applying discounts
$new_subtotal = $original_subtotal - $total_discount;
// Ensure subtotal is not negative
if ( $new_subtotal < 0 ) {
$new_subtotal = 0;
}
// Return formatted subtotal
return wc_price( $new_subtotal );
}
add_filter( 'woocommerce_cart_item_subtotal', 'custom_cart_item_subtotal', 10, 3 );
0 Response to " Change subtotal after coupon discount applied Woocommerce"
Post a Comment
Komentar yang Anda kirim akan terlebih dahulu di moderasi oleh Admin