Join

Automatically Apply a WooCommerce Coupon and Redirect to the Cart Page Using a Link

Don't want to mess with code snippets? This is 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

Use Cases

Direct URL to the Cart Page With the Coupon Code ‘Partner’.

The link below can be used when a particular coupon is applicable to all of the items in the cart.

https://domain.com/cart/?coupon=partner

Add a Specific Product (By Product ID) to the Cart and Automatically Apply the Coupon Code ‘Partner’.

The ‘123’ portion of the example link below, references the specific product’s ID. The Product ID can be found by going to WordPress Dashboard > Products and hovering over the product name.

https://domain.com/cart/?add-to-cart=123&coupon=partner

Code Snippet

<?php 

/* Apply a WooCommerce discount code to cart via URL parameter. */

function my_woocommerce_apply_cart_coupon_in_url() {
	// Return early if WooCommerce or sessions aren't available.
	if ( ! function_exists( 'WC' ) || ! WC()->session ) {
		return;
	}

	// Return if there is no coupon in the URL, otherwise set the variable.
	if ( empty( $_REQUEST['coupon'] ) ) {
		return;
	} else {
		$coupon_code = esc_attr( $_REQUEST['coupon'] );
	}

	// Set a session cookie to remember the coupon if they continue shopping.
	WC()->session->set_customer_session_cookie(true);

	// Apply the coupon to the cart if necessary.
	if ( ! WC()->cart->has_discount( $coupon_code ) ) {

		// WC_Cart::add_discount() sanitizes the coupon code.
		WC()->cart->add_discount( $coupon_code );
	}
}
add_action('wp_loaded', 'my_woocommerce_apply_cart_coupon_in_url', 30);
add_action('woocommerce_add_to_cart', 'my_woocommerce_apply_cart_coupon_in_url');

Video Tutorial

Youtube video