Created
May 4, 2020 08:19
-
-
Save PhongGCS/8c2c2d79b826e325a6d8e01406f0b394 to your computer and use it in GitHub Desktop.
Auto add coupon in woocommerce with sample attribute variation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action( 'woocommerce_before_cart', 'cs_apply_matched_coupons' ); | |
function cs_apply_matched_coupons() { | |
global $woocommerce; | |
$coupon1 = 'coupon 1'; // your coupon code here | |
$coupon2 = 'coupon 2'; // your coupon code here | |
$coupon3 = 'coupon 3'; // your coupon code here | |
$coupon4 = 'coupon 4'; // your coupon code here | |
$coupon5 = 'coupon 5'; // your coupon code here | |
$sample_count = 0; | |
$cartData = $woocommerce->cart->cart_contents; | |
foreach ( $cartData as $cart_item ) { | |
$attribute = $cart_item['data']->get_variation_attributes(); | |
if( !empty($attribute['attribute_pa_product-type']) && $attribute['attribute_pa_product-type'] == 'sample') { | |
$sample_count += $cart_item['quantity']; | |
} | |
} | |
$sample_count = (int) $sample_count; | |
if ( $sample_count == 1 ) { | |
$woocommerce->cart->add_discount( $coupon1 ); | |
} elseif ( $sample_count == 2 ) { | |
$woocommerce->cart->add_discount( $coupon2 ); | |
} elseif ( $sample_count == 3 ) { | |
$woocommerce->cart->add_discount( $coupon3 ); | |
} elseif ( $sample_count == 4 ) { | |
$woocommerce->cart->add_discount( $coupon4 ); | |
} elseif ( $sample_count >= 5 ) { | |
$woocommerce->cart->add_discount( $coupon5 ); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment