This code snippet is versatile, providing the ability to assign coupons when various links are used.
The key thing to note when looking at this snippet and the URL examples I’ll show you is the ‘coupon_code’ portion of Line 9. In short, each URL must contain ‘coupon_code’ for the coupon to trigger.
function wptu_woocommerce_coupon_links(){
// Bail if WooCommerce or sessions aren't available.
if (!function_exists('WC') || !WC()->session) {
return;
}
$query_var = apply_filters('woocommerce_coupon_links_query_var', 'coupon_code');
// Bail if a coupon code isn't in the query string.
if (empty($_GET[$query_var])) {
return;
}
// Set a session cookie to persist the coupon in case the cart is empty.
WC()->session->set_customer_session_cookie(true);
// Apply the coupon to the cart if necessary.
if (!WC()->cart->has_discount($_GET[$query_var])) {
// WC_Cart::add_discount() sanitizes the coupon code.
WC()->cart->add_discount($_GET[$query_var]);
}
}
add_action('wp_loaded', 'wptu_woocommerce_coupon_links', 30);
add_action('woocommerce_add_to_cart', 'wptu_woocommerce_coupon_links');Customization Notes
Apply a Coupon to the Entire Cart
With this example, the coupon code you use in the URL will be applied to the entire cart.
- Add the code snippet to your site.
- Create a coupon.
- Use the URL below to trigger the coupon, adjusting it for your domain and coupon code.
https://example.com/cart/?coupon_code=YOURCOUPONCODEApply a Coupon to Any Product
With this example, we apply a coupon code to a specific product, add that product to the cart, and bring up the checkout page.
- Add the code snippet to your site.
- Create a coupon.
- Use the URL below to trigger the coupon, adjusting it for your domain, product, and coupon code.
The ‘=12345’ portion of the URL below is the Product ID, which can be obtained by hovering over the desired WooCommerce product.
https://example.com/checkout/?add-to-cart=12345&coupon_code=YOURCOUPONCODE