Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirejordansmith/2e1a9d7c8e5985fef6f7c945ae60ebfa to your computer and use it in GitHub Desktop.
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
<?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