Created
December 2, 2020 20:57
-
-
Save contemplate/794a665c5e0b10f2e22edb71bd67cc2d to your computer and use it in GitHub Desktop.
Smart Coupons By URL Cartflows integration
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
/*-- Smart Coupons By URL Integration --*/ | |
add_action( 'cartflows_checkout_after_configure_cart', 'cartflows_smart_coupons_apply_coupon_from_url', 10, 1 ); | |
function cartflows_smart_coupons_apply_coupon_from_url( $checkout_id ) { | |
$cart = ( is_object( WC() ) && isset( WC()->cart ) ) ? WC()->cart : null; | |
parse_str( wp_unslash( $_SERVER['QUERY_STRING'] ), $coupon_args ); // phpcs:ignore | |
$coupon_args = wc_clean( $coupon_args ); | |
// If Coupons are in URL | |
if ( isset( $coupon_args['coupon-code'] ) && ! empty( $coupon_args['coupon-code'] ) ) { | |
$coupon_args['coupon-code'] = urldecode( $coupon_args['coupon-code'] ); | |
$coupon_codes = explode( ',', $coupon_args['coupon-code'] ); | |
$coupon_codes = array_filter( $coupon_codes ); // Remove empty coupon codes if any. | |
$cart = ( is_object( WC() ) && isset( WC()->cart ) ) ? WC()->cart : null; | |
$coupons_data = array(); | |
foreach ( $coupon_codes as $coupon_index => $coupon_code ) { | |
// Process only first five coupons to avoid GET request parameter limit. | |
if ( apply_filters( 'wc_sc_max_url_coupons_limit', 5 ) === $coupon_index ) { | |
break; | |
} | |
if ( empty( $coupon_code ) ) { | |
continue; | |
} | |
$coupons_data[] = array( | |
'coupon-code' => $coupon_code, | |
); | |
} | |
//set a cookie for storing of 1 hour | |
wc_setcookie( 'sc_applied_url_coupon_cartflow', json_encode($coupons_data), time()+3600 ); | |
// apply them now if nothing stops us | |
if ( $cart ) { | |
foreach ( $coupons_data as $coupon_data ) { | |
$coupon_code = $coupon_data['coupon-code']; | |
if ( ! WC()->cart->has_discount( $coupon_code ) ) { | |
WC()->cart->add_discount( trim( $coupon_code ) ); | |
} | |
} | |
} | |
// Or check if we put them in a cookie | |
} else { | |
if( ! empty( $_COOKIE['sc_applied_url_coupon_cartflow'] ) ){ | |
$applied_coupon_from_url = wc_clean( wp_unslash( $_COOKIE['sc_applied_url_coupon_cartflow'] ) ); | |
$applied_coupon_from_url = json_decode($applied_coupon_from_url, true); | |
} else { | |
return; | |
} | |
foreach ( $applied_coupon_from_url as $index => $coupon_code ) { | |
$coupon = new WC_Coupon( $coupon_code['coupon-code'] ); | |
if ( $coupon->is_valid() && ! WC()->cart->has_discount( $coupon_code['coupon-code'] ) ) { | |
WC()->cart->add_discount( trim( $coupon_code['coupon-code'] ) ); | |
unset( $applied_coupon_from_url[ $index ] ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment