How to use same coupon with multiple discount type?

Hi Dev’s,

Here, I will share my experience to use same coupon  with different discount type depending up-one the product added in cart. Here possible solution can be having discount rules added on coupon or take help of plugin which can do so, And another option will be filtering on such way that we can follow coupon management process to create multiple coupon with same name and add filter which will pick specific coupon id meant for specific product.

Note: It's better practice to have distinct coupon in the system so please implement 
carefully before you add this code to production
/**
* @param int $wc_id
* @param string code
* @param int    $exclude Used to exclude an ID from the check if you're checking existence.
* @return ids
* This can switch the coupon ids depending upone the coupon type
*/
add_filter( 'woocommerce_get_coupon_id_from_code', function( $wc_id, $code, $exclude ) {
	$has_coupon_multiple_ids  = wp_cache_get( WC_Cache_Helper::get_cache_prefix( 'coupons' ) . 'coupon_id_from_code_' . $code, 'coupons' );
	if( is_array( $has_coupon_multiple_ids ) && count( $has_coupon_multiple_ids) > 1 ) {
		foreach ( $has_coupon_multiple_ids as $key => $id ) {
			$id = absint(  $id );
			$the_coupon =  new WC_Coupon( $id );
			if( $this->swap_coupon( $the_coupon, $id ) ) {
				return $id;
			}
		}
	}
	return $wc_id;
}, 10, 3 );

/**
* It swap the coupon id when added from cart or admin order page
* @param Wc_Coupon $coupon
* @param int $coupon_id
*/
function swap_coupon( $coupon, $coupon_id ) {
	if( current_user_can( 'edit_shop_orders' ) && 
		isset( $_POST[ 'order_id' ] ) && 
		0 !== absint(  $_POST[ 'order_id' ] ) && 
		"woocommerce_add_coupon_discount" === $_POST[ 'action' ] 
	) {
		$order = wc_get_order( absint( $_POST[ 'order_id' ] ) );
		if( is_null( $order ) || empty( $order ) ) return false;
		$discounts = new WC_Discounts( $order );
		$is_valid =  $discounts->is_coupon_valid( $coupon );
		if( is_wp_error( $is_valid ) ) {
			return false;
		} else {
			return $coupon_id;
		}
	} else {
		if( $coupon->is_valid() ) {
			return $coupon_id;
		}
	}
	return false;
}

Here the logic added is simple, we are just swapping the coupon that fits well on given product.

Hope this may help you on someway on dev journey.

Thanks

Advertisement

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: