Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.