Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Create a URL That Applies a Discount & Adds Products to WooCommerce Cart?

By default, WooCommerce enables you to generate URL coupons in WooCommece manually. One good way is to bypass manually entering coupon codes! This could also reduce the number of customers leaving your site looking for discount coupon codes.

You can create unique coupon links or URLs for each coupon and offer them to the customers instead of raw coupons. Coupon links are an alternative to our conventional coupon code approach, enabling applying coupons using a URL. In addition to discount coupons, you can also attach products with coupon URLs.

This post will guide you on how to create a URL that applies a discount and adds products to the WooCommerce cart.

Where to Add Custom Code in WooCommerce?

It is advisable to add the code snippets to the functions.php file of your child theme. Access the file directly from Appearance->Theme File Editor->Locating the child theme’s functions.php from the right sidebar. You can also access it from your theme’s directory file. Insert the following code snippet in functions.php. The alternative & easy option is to install & activate the Code Snippets plugin. You can then add the code as a new snippet via the plugin.

Preliminary Steps

Here’s a general guide on how you can create a coupon and construct such a URL:-

Creating Coupon:

Before applying the code snippet, you need to first create the coupon code in the backend. Follow the steps below:-

  1. Navigate to the WooCommerce admin.
  2. Go to “Marketing” > “Coupons.”
  3. Click “Add Coupon.”

For E.g. – I have set up a coupon code called “cybermonday”.

How to Create a URL That Applies a Discount & Adds Products to WooCommerce Cart? - Tyche Softwares

Applying a Discount Code & Adding Products:

To apply a discount code and add products, use the following URL parameters:

  • apply_coupon: The coupon code you want to apply.
  • add-to-cart: Comma-separated list of product IDs.
  • quantity: The quantity of each product.
http://127.0.0.1/wordpress/?page_id=7&apply_coupon=your_coupon_code&add_to_cart=product_id&quantity=1,2

Solution: Create a URL That Applies a Discount and Adds Products to the WooCommerce Cart

An online store is offering a deal where customers can get a discount on their purchase by entering a coupon code along with its product ID and quantity in the URL. They want to simplify the process by automatically applying the coupon code to the cart when customers visit the site.

The below snippets provide the functionality for the store to automatically apply the coupon code & product to the cart.

function ts_add_to_cart_and_apply_coupon() {
    // Check if WooCommerce is active and sessions are available.
    if ( class_exists( 'WooCommerce' ) && WC()->session ) {

        // Check if products are specified in the URL to add to the cart.
        if ( isset( $_GET['add_to_cart'] ) && ! empty( $_GET['add_to_cart'] ) ) {
            $product_ids = explode( ',', sanitize_text_field( $_GET['add_to_cart'] ) );
            $quantity = isset( $_GET['quantity'] ) ? explode( ',', sanitize_text_field( $_GET['quantity'] ) ) : array();

            // Loop through product IDs and add them to the cart.
            foreach ( $product_ids as $key => $product_id ) {
                $quantity_to_add = isset( $quantity[ $key ] ) ? $quantity[ $key ] : 1;
                WC()->cart->add_to_cart( $product_id, $quantity_to_add );
            }
        }

        // Check if coupon code is provided in the URL.
        if ( isset( $_GET['apply_coupon'] ) && ! empty( $_GET['apply_coupon'] ) ) {
            $coupon_code = sanitize_text_field( $_GET['apply_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( $coupon_code );
            }
        }
    }
}

add_action( 'wp_loaded', 'ts_add_to_cart_and_apply_coupon', 30 );

Output

When the coupon code “cybermonday”, product ID (23), and quantity are entered in the URL, the system automatically applies the coupon amount to the cart subtotal and adds the product to the cart table on the WooCommerce cart page.

URL That Applies a Discount & Adds Products to WooCommerce Cart
flexi bogo cta banner image


This to the shop owners who are running or planning to run BOGO offers on their WooCommerce store…

BOGO deals are great for increasing your sales, but have you thought about which offers are bringing you more revenue and which offers are not performing that great?

Don’t just set a BOGO deal, track the revenue generated by your deals in real-time with the Flexi BOGO for WooCommerce plugin.

Code Explanation

Function: ts_apply_coupon_and_add_to_cart()

This function is designed to be hooked into the WordPress action wp_loaded. It checks if WooCommerce is active and sessions are available. If so, it performs two main tasks: applying a coupon code and adding products to the cart based on the parameters provided in the URL.

Check for WooCommerce and Sessions

This part checks if the WooCommerce class exists, indicating that the WooCommerce plugin is active, and if the session is available.

Applying a Coupon Code

If a coupon code is provided in the URL (using the ‘apply_coupon‘ parameter), it sanitizes the input and checks if the coupon is not empty. Then, it sets a customer session cookie and applies the coupon to the cart if it’s not already applied.

Adding Products to the Cart

If products are specified in the URL (using the ‘add_to_cart’ parameter), it sanitizes the input and checks if the product list is not empty. It then processes product IDs and quantities (if provided) and adds them to the cart.

Applying Quantity to Products

If quantities are provided in the URL (using the ‘quantity’ parameter), it sanitizes the input and converts it into an array. This array is then used to determine the quantity to add for each product.

Looping Through Product IDs and Adding to Cart

This loop iterates through the product IDs and adds them to the cart using the add_to_cart method. If a quantity is specified for a product, it uses that quantity; otherwise, it defaults to 1.

Hooking the Function

This line hooks the ts_apply_coupon_and_add_to_cart function to the wp_loaded action with a priority of 30. The priority determines the order in which multiple functions hooked to the same action are executed. In this case, it ensures that the function runs relatively early during the WordPress loading process.

Conclusion

The above snippets handle two scenarios: applying a coupon code specified in the URL and adding products to the cart based on product IDs and quantities provided in the URL. Alternatively, you can also auto apply the coupon programatically in WooCommerce without modifying the URL.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
4 Comments
Newest
Oldest
Inline Feedbacks
View all comments
3 months ago

Works perfectly! Thanks so much for your contribution.

Kay
4 months ago

Thanks for sharing. If you coupon is only valid for specific products then you need to run your add products to cart script before the add coupon script. I had this issue and swapped the order to fix it.

Editor
4 months ago
Reply to  Kay

Hi Kay,

That’s right to swap the order of operations to avoid coupon validity issues if the coupon is restricted to specific products only. We’ve updated the post to reflect this change.

Sudaram
8 months ago

Hi prateek,

Thanks for sharing this amazing snippets, it really help me alot and also I could able implement this snippet for my client projects.

Once again thanks alot.

4
0
Would love your thoughts, please comment.x
()
x