Join

Automatically Apply a Coupon When a Link is Used

Don't want to mess with code snippets? Request for this to be a feature of MyListing Pro.

Instructions

  1. Create a new PHP code snippet.
  2. Copy the contents of code snippet below.
  3. Paste the contents into your code snippet.
  4. Review any notes that I’ve provided.
  5. Save and enable the code snippet.
  6. Test.

Snippet

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.

  1. Add the code snippet to your site.
  2. Create a coupon.
  3. Use the URL below to trigger the coupon, adjusting it for your domain and coupon code.
https://example.com/cart/?coupon_code=YOURCOUPONCODE

Apply 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.

  1. Add the code snippet to your site.
  2. Create a coupon.
  3. 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

Video Tutorial