Created
May 15, 2020 20:00
-
-
Save xlawok/0224f8ddf4233aadb2071a6bb2837606 to your computer and use it in GitHub Desktop.
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
function woocommerce_detect_coupon_code() { | |
// Check if custom URI with coupon URL is requested | |
if(!empty($_GET['code'])) { | |
// Check if cart/shop page is set & redirect to it | |
// $shop_page_id = wc_get_page_id('shop'); | |
// $cart_page_id = wc_get_page_id('cart'); | |
if(!empty($cart_page_id) && WC()->cart->get_cart_contents_count() > 0) { | |
// $redirect_page = $cart_page_id; | |
// } | |
// else if(!empty($shop_page_id)) { | |
// $redirect_page = $shop_page_id; | |
// } | |
$coupon_code = sanitize_text_field($_GET['code']); | |
// Set-up session | |
if(!WC()->session->has_session()) { | |
WC()->session->set_customer_session_cookie(true); | |
} | |
// Add the discount code | |
if(!WC()->cart->has_discount($coupon_code)) { | |
WC()->cart->add_discount($coupon_code); | |
} | |
// Do redirect | |
if(!empty($redirect_page)) { | |
wp_safe_redirect( wc_get_page_permalink( 'shop' )); | |
exit(); | |
} | |
} | |
} | |
add_action('template_redirect', 'woocommerce_detect_coupon_code', 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment