Last active
March 7, 2019 09:00
-
-
Save hirejordansmith/2e1a9d7c8e5985fef6f7c945ae60ebfa to your computer and use it in GitHub Desktop.
Create Product Bundles by adding coupons to cart dynamically based on products in the cart - WooCommerce
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
<?php | |
/** | |
* Hire Jordan Smith // Create Product Bundles by adding coupons to cart dynamically based on products in the cart | |
* | |
* @version 1.0 | |
* @author Jordan Smith <jordan@hirejordansmith.com> | |
* @license GPL-2.0+ | |
* @link http://hirejordansmith.com/... | |
* @copyright 2016 - Hire Jordan Smith | |
*/ | |
add_action( 'woocommerce_before_cart', 'hjs_add_hat_panty_bundle_coupon' ); | |
function hjs_add_hat_panty_bundle_coupon() { | |
global $woocommerce; | |
// Replace 'hatpantybundle2016' with your coupon code | |
$coupon_code = 'hatpantybundle2016'; | |
// Create Empty Array | |
$cart_product_ids = []; | |
// Build Array of Product Id's for Cart Products | |
foreach ($woocommerce->cart->cart_contents as $key => $ids ) { | |
$cart_product_ids[] = $ids['product_id']; | |
} | |
// Numbers represent Product IDs | |
if (in_array( 1507, $cart_product_ids) && in_array(1320, $cart_product_ids)) { | |
if ( $woocommerce->cart->has_discount( $coupon_code ) ) return; | |
foreach ($woocommerce->cart->cart_contents as $key => $values ) { | |
$autocoupon = array(1507, 1320); | |
if (in_array( $values['product_id'], $autocoupon) ){ | |
$woocommerce->cart->add_discount( $coupon_code ); | |
wc_print_notices(); | |
if ( $woocommerce->cart->has_discount( $coupon_code ) ) return; | |
} | |
} | |
} else { | |
// This will automatically remove the coupon if it's already added | |
// I had this in place because I was doing more than one of these so it resets the cart | |
$woocommerce->cart->remove_coupon( $coupon_code ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment