'Apply a Coupon automatically for Product Category or Multiple categories - Woocommer 5.9
This is regarding Woocommerce (using version 5.9) - to apply coupon code automatically when below condition met.
I am using below code to Automatically apply coupon on products (or multiple products in an array), on the basis of Product ID (here, in our case say, 7974).
This works perfectly fine, when the same product is in Cart (for which the ID is mentioned or multiple IDs in an array, in below code snippet)
However, I want to have the Coupon Applied automatically for ALL products from a particular or specified Product Category (Say Bags, or Kurtis).
- So, what we need to change or update in the below code, so as to apply the Coupon for the whole product category or multiple categories (with their IDs in array), automatically.
As adding each product ID manually is not possible and very cumbersome. Specially, when one have lots of products in each category.
- Also, do we need to use the Slug of product category, or ID or some other (on that updated code)
add_action( 'woocommerce_before_cart', 'vas_apply_matched_coupons' );
function vas_apply_matched_coupons() {
$coupon_code = 'less120';
if ( WC()->cart->has_discount( $coupon_code ) ) return;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// this is your product ID
$autocoupon = array( 7974 );
if ( in_array( $cart_item['product_id'], $autocoupon ) ) {
WC()->cart->apply_coupon( $coupon_code );
wc_print_notices();
}
}
}
Can you please suggest on this and share the updated code, in order to work with whole product category, rather than adding each product ID manually in this code snippet.
Regards
Solution 1:[1]
First of all, do not use the woocommerce_before_cart hook: it's a template hook used to render something before the WooCommerce cart. It makes more sense to use the woocommerce_before_calculate_totals instead.
If you want to apply a coupon if there's at least one product from the specific category, your code should look like this:
add_action( 'woocommerce_before_calculate_totals', 'auto_apply_coupon_for_specific_categories', 10, 1 );
function auto_apply_coupon_for_specific_categories( $cart ) {
$coupon_code = 'less120';
if ( $cart->has_discount( $coupon_code ) ) {
return;
}
$discount_categories = array(1,2,3); // an array of terms IDs or slugs
$coupon_should_be_applied = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$product_belongs_to_discount_category = has_term( $discount_categories, 'product_cat', $product_id );
if ( $product_belongs_to_discount_category ) {
$coupon_should_be_applied = true;
break;
}
}
if ( ! $coupon_should_be_applied ) {
return;
}
$cart->apply_coupon( $coupon_code );
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Artemy Kaydash |
