I am trying to add a coupon code automatically if the cart has products from specific categories. The price must be updated in the Total after showing the discount amount.
But I cant see any changes in the total, kindly help me.
My code:
add_action('wc_cart_product_subtotal' , 'getsubtotalc');
function getsubtotalc ($product_subtotal, $_product, $quantity, $object) {
if( is_cart() || is_checkout() ) {
global $woocommerce, $product;
global $total_qty;
/*$coupon_code = 'drawer';
if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;*/
foreach ( $woocommerce->cart->cart_contents as $product ) {
if( has_term( array('t-shirts-d','socks-d','joggers-d','boxers-d'), 'product_cat', $cart_item['product_id'] ) ){
$coupon_code = 'drawer';
if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code))) {
$woocommerce->show_messages();
}
echo '<div class="woocommerce_message"><strong>The number of Product in your order is greater than 10 so a 10% Discount has been Applied!</strong>
</div>';
}
}
}
}
Thanks
Here is the correct hook and code, that will auto apply a coupon code when a cart item is from specific product categories and will update cart totals:
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Code is tested on woocommerce 3+ and works.