IN WooCommerce I would like to add 10% of discount with WooCommerce Coupon feature, only when customer purchases products from 3 different product categories (like Category1, Category2, Category3).
How this can be done with WooCommerce Coupon feature?
Any help on this will be appreciated.
Update note: I only 3 parent product categories with no sub categories. Each product is assigned to one category. Some products are variable and some others are simple.
To handle this functionality with a coupon you will need to have one product category by product or one parent category by product, because a product can have many categories and subcategories set for it.
This custom function will add a coupon discount when cart items are from 3 different product categories. If cart items are removed from cart and there is not anymore 3 different product categories, the coupon code will be auto removed.
Also you will need to set in the function the coupon code name and an array of all your matching product categories IDs.
Here is the code:
add_action( 'woocommerce_before_calculate_totals', 'add_discount_for_3_diff_cats', 10, 1 );
function add_discount_for_3_diff_cats( $wc_cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE set your coupon code and your parent product categories in the array
$coupon_code_to_apply = 'summer';
// HERE define your product categories IDs in the array
$your_categories = array( 11, 13, 14 ); // IDs
// If coupon is already set
if( $wc_cart->has_discount( $coupon_code_to_apply ) )
$has_coupon = true;
foreach( $wc_cart->get_cart() as $cart_item ) {
$product_id = $cart_item['product_id'];
$product = wc_get_product($product_id);
foreach( $product->get_category_ids() as $category_id ) {
if( has_term( $your_categories, 'product_cat', $product_id ) && in_array( $category_id, $your_categories ) ){
// Set the categories in an array (avoiding duplicates)
$categories[$category_id] = $category_id;
}
}
}
$count_cats = count($categories);
$has_discount = $wc_cart->has_discount( $coupon_code_to_apply );
if ( 3 <= $count_cats && ! $has_discount ) {
$wc_cart->add_discount($coupon_code_to_apply);
} elseif ( 3 > $count_cats && $has_discount ) {
$wc_cart->remove_coupon($coupon_code_to_apply);
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works with simple and variable products…