Created
September 13, 2017 16:05
-
-
Save ThatGuySam/db2854d006e0469a6bace59182343ffb to your computer and use it in GitHub Desktop.
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
function bbloomer_add_gift_if_sku_added_cart( $passed, $product_id, $quantity ) { | |
global $woocommerce; | |
$skuswithgift = array('SMWB-M23','001-SLW'); | |
$giftsku = 'comb'; | |
$coupon_code = 'combfree'; | |
$product = wc_get_product( $product_id ); | |
$total_towels = 0; | |
// Determine how many towels there are | |
// Loop through every cart item | |
foreach ( $woocommerce->cart->get_cart() as $cart_item ) { | |
// $product = $cart_item['data']; | |
$product = $cart_item; | |
// Is it in Gift SKUs | |
$is_towel = in_array($product->get_sku(), $skuswithgift); | |
if($is_towel){ | |
// Add this quantity to the total towels | |
$total_towels += $cart_item['quantity']; | |
} | |
} | |
// Apply Discount | |
if ($total_towels < 1) { | |
WC()->cart->add_to_cart( wc_get_product_id_by_sku($giftsku) ); | |
wc_add_notice( __( 'Hey there! As promised, you recieved a free comb with the purchase of two towels and we added it to your cart for you!', 'woocommerce' ), 'success' ); | |
$woocommerce->cart->add_discount( $coupon_code ); | |
} | |
else { | |
WC()->cart->remove_cart_item( wc_get_product_id_by_sku($giftsku) ); | |
$woocommerce->cart->remove_coupon( $coupon_code ); | |
} | |
return $passed; | |
} | |
add_filter( 'woocommerce_add_to_cart_validation', 'bbloomer_add_gift_if_sku_added_cart', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment