Add Discount to Cart Programmatically in WooCommerce

How to Add Discount to Cart Programmatically in WooCommerce (Easy Steps)

Discounts and coupons are the most powerful marketing tool for an online store. They can give you a 73% boost in your sales.

Here are some awestriking stats on the impact of discounts –

  • 97% of online shoppers look for discounts before buying.
  • A coupon can increase sales by 85%.
  • 38% of buyers spend more because they have a coupon.
  • 80% of consumers will buy from a different store if offered an attractive promotion.
  • 81% of consumers will join a loyalty program for discounts.
  • Over 80% of Americans sign up for emails to get discounts.
  • 65% of consumers will try a new product for a discount code.
  • 68% agree that discounts build brand recognition and loyalty.

I hope this proves the might and power of discounts. WooCommerce is the best platform to build an online store and run discount campaigns effectively.

WooCommerce offers a robust coupon system, but for even more control and automation, you can leverage programmatic discounts. That is our topic of discussion today.

We will explain what the term WooCommerce add discount to cart programmatically means and how you can achieve this.

Let’s get started.

What Does Is It Mean by WooCommerce Add Discount to Cart Programmatically

WooCommerce has a built-in coupon tool that allows you to create coupon codes. Customers must enter the coupon code manually on the cart page to avail of the discounts.

WooCommerce programmatically adds discounts to carts, or Programmatic discounts take a different approach. Here’s how it works:

Instead of customers entering a code, you automatically use some codes or plugins to apply discounts to the cart based on pre-defined conditions.

Here’s an analogy:

  • Traditional Coupon: Like a physical coupon a customer hands over at checkout.
  • Programmatic Discount: Like a store’s automatic sale that adjusts the price based on certain criteria (e.g., buy 2 get 1 free).

Benefits of Programmatic Discounts

We will discuss the benefits in detail later in the article, but here’s a quick review.

  • Automation: Set up discounts once, and they run automatically.
  • Conditional Discounts: Offer discounts based on specific criteria (e.g., cart total, product category).
  • Targeted Promotions: Tailor discounts to specific customer segments.

How to Apply Discount to WooCommerce Cart Programmatically

There are two ways you can assign WooCommerce add discount to cart programmatically.

  1. Using custom codes
  2. Using a discount plugin

WooCommerce Add Discount to Cart Programmatically Using Codes

In our blog, we have covered an array of articles on different types of discounts. In those articles, we have shown how to automatically apply discounts using custom codes.

This article will walk you through the basic process of adding custom codes to apply discounts programmatically/automatically. First, let us explain how to add custom codes in WooCommerce.

Adding Custom Codes in WooCommerce

If you are wondering how can I add a discount to a WooCommerce cart using a code, here’s the step-by-step process.

Step 1: Backup Your Site

Before making any changes, always back up your WordPress site. You can use plugins like UpdraftPlus or manually back up your files and database. Alternatively, you can create a child theme.

Step 2: Access Your WordPress Dashboard

Log in to your WordPress admin panel.

Step 3: Choose How to Add Custom Code

You have multiple options to add custom code:

  1. Theme’s functions.php File
  2. Custom Plugin
  3. Code Snippets Plugin

We will go with the direct functions.php file edit for this article. Access functions.php by going to Appearance>>Theme File Editor and clicking on the functions.php file.

Theme file editor

Scroll to the bottom of the file and hit enter to create a new empty space for inserting your codes.

function file

Programmatically Apply Coupons To The Cart

WooCommerce’s built-in tool for offering discounts is the Coupon tool.

coupon tool

With this tool, you can create fixed-amount discounts, fixed product discounts, or percentage discount coupon codes based on –

  • Cart amount
  • Specific products
  • Product categories
  • Specific emails/users

Along with these, you can also create and offer a free shipping coupon using the default tool. However, the coupon tool doesn’t let WooCommerce add discount to cart programmatically.

To achieve that, you can add some custom codes to the WooCommerce theme file. This code will automatically apply the coupon discount on the cart page without your user inserting it manually.

As we have explained, go to functions.php and enter the following code –

/**

 * WebAppick – Apply Discount Coupon automatically to the cart

 */

function ts_apply_discount_to_cart() {

$order_total = WC()->cart->get_subtotal();

if( $order_total > 100 ) {

     $coupon_code = '10OFF';

     if ( !WC()->cart->apply_coupon( sanitize_text_field( $coupon_code ) ) ) {

         wc_print_notices();

     }

}

}

add_action( 'woocommerce_before_cart_table', 'ts_apply_discount_to_cart' );

This will automatically apply the coupons to the cart page.

woocommerce add discount to cart programmatically

Next, we will review some conditional discount codes that don’t require any coupons.

WooCommerce Add Discount to Cart Programmatically Based On Cart Total

Let’s check out how you can add custom codes to offer discounts based on cart subtotal.

Let’s say you want to offer a 15% discount when the cart subtotal is $100 or more.

Go to funcitons.php and insert the following code.

add_action( 'woocommerce_cart_calculate_fees', 'custom_discount_for_cart_total', 20, 1 );

function custom_discount_for_cart_total( $cart ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {

     return;

}

// Define the minimum cart total for the discount

$minimum_cart_total = 100;

// Define the discount percentage

$discount_percentage = 15;

// Calculate the cart total

$cart_total = $cart->cart_contents_total;

// Check if the cart total meets the minimum requirement

if ( $cart_total >= $minimum_cart_total ) {

     // Calculate the discount

     $discount = $cart_total * ($discount_percentage / 100);

     // Add the discount to the cart

     $cart->add_fee( sprintf( __( '15%% Discount for orders over $%s', 'text-domain' ), $minimum_cart_total ), -$discount );

}

}

Update the file and add some products in the front end to test the code.

woocommerce add discount to cart programmatically

As you can see, the cart programmatically applied the discounts when the subtotal reached over 100. You can also call this a WooCommerce percentage discount.

BOGO Discounts – WooCommerce Add Discount to Cart Programmatically

Buy One Get One, or BOGO discounts are immensely popular amongst all types of customers. 

Here’s a code for offering BOGO. You can offer customers a free quantity of the same product they ordered using this code.

function add_bogo_free_product() {

$cart = WC()->cart->get_cart();

// Loop through cart items to check products

foreach ($cart as $cart_item_key => $cart_item) {

  $product_id = $cart_item['product_id'];

  $quantity = $cart_item['quantity'];

  // Ensure no free items are added

  if (!isset($cart_item['custom_price']) && $quantity > 0) {

      // Check if a free product is already in the cart

      $free_product_exists = false;

      foreach ($cart as $free_cart_item_key => $free_cart_item) {

          if ($free_cart_item['product_id'] == $product_id && isset($free_cart_item['custom_price'])) {

              $free_product_exists = true;

              break;

          }

      }

      // Add free products if not already in the cart

      if (!$free_product_exists) {

          WC()->cart->add_to_cart($product_id, $quantity, 0, array(), array('custom_price' => 0));

      }

  }

}

}

add_action('woocommerce_before_calculate_totals', 'add_bogo_free_product');

function apply_bogo_custom_price($cart_object) {

foreach ($cart_object->get_cart() as $cart_item) {

  if (isset($cart_item['custom_price'])) {

      $cart_item['data']->set_price($cart_item['custom_price']);

  }

}

}

add_action('woocommerce_before_calculate_totals', 'apply_bogo_custom_price');

Here’s what the cart page returns when a customer adds any product.

woocommerce add discount to cart programmatically

You can take a look at our full guide on BOGO deals for more codes and programmatic discount solutions.

First-Order Discounts WooCommerce Add Discount To Cart Programmatically

First-order discounts can entice your visitors to make the purchase decision. This discount can be a powerful tool for converting visitors into buying customers.

The following code is for the customers who have newly registered an account in your store and are buying something for the first time.

// Apply first-order discount for new customers

function apply_first_order_discount() {

// Ensure the function only runs in the frontend

if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

if ( is_user_logged_in() ) {

  $current_user = wp_get_current_user();

  $user_orders = wc_get_orders( array(

      'customer' => $current_user->ID,

      'limit' => 1,

  ) );

  // If the user has no previous orders, apply the discount

  if ( empty( $user_orders ) ) {

      add_action( 'woocommerce_cart_calculate_fees', 'add_first_order_discount' );

  }

}

}

add_action( 'wp', 'apply_first_order_discount' );

// Function to add the discount

function add_first_order_discount() {

$discount_amount = 10; // Set your discount amount here

WC()->cart->add_fee( __( 'First Order Discount', 'woocommerce' ), -$discount_amount );

}

Similarly, you can add code to programmatically/automatically apply discounts for specific categories, products, bundles, and other conditional discounts.

However, we must mention that using custom codes involves considerable risk. We don’t recommend using them if you are not familiar with codes.

So, what is the best method for adding programmatic discounts to a WooCommerce cart?

Third-party discount plugins. Let’s check out how WooCommerce add discount to cart programmatically using a plugin.

How to Apply Discount to WooCommerce Cart Programmatically Using a Plugin

There are a plethora of discount plugins available in the market. These plugins allow you to create discounts based on a wide range of conditions with minimum effort.

The plugin we will use for this article is Disco—Dynamic Discount Plugin for WooCommerce. It is by far the most advanced plugin we have tested so far, and the best thing about it is that it is completely Free!

Moreover, it contains all the possible features you can imagine that you only can find on a paid premium plugin.

Disco discount plugin

With Disco, you can offer your customers a large variety of discounts, including percentage or fixed-amount discounts, cart-based discounts, purchase history-based discounts, and product attribute-based discounts. You can also schedule discounts and create BOGO (Buy One, Get One) offers.

Additionally, Disco allows you to target specific products, categories, or product variations for your discounts. Let’s install the plugin from the WordPress repository and create some automatic discounts.

Install Disco

After installing and activating, click on the Disco option from the main menu.

create woocommerce add discount to cart programmatically

Click on the Create a Discount button. It will take you to the following window.

woocommerce add discount to cart programmatically

Let us walk you through the sections.

First, you need to set a discount name for your campaign. Then, select the type of discount you want to create from the Discount Intention field.

campaign discount

From the Discount section, you can filter specific products, set user limits and expiration dates for WooCommerce add discount to cart programmatically.

discount tab

The Product Rules tab will change based on what you select in the Discount Intention field. You need to set the discount value here.

product rules

The Condition tab is what makes this plugin so rich. You can assign and apply an incredible range of conditions to your automatic discounts from this field.

conditions for woocommerce add discount to cart programmatically

Let’s create some discounts.

Creating Product-Based Programmatic Discounts Using a Plugin

Let’s say we want to offer a 20% discount on some specific products. Start by selecting the Product option from the Discount Intention field.

few products

To select specific products, select the Few Products tab. Search and select the products.

select product

Select the Percentage option from the Product Rules >> Discount Type.

discount percentage

Input your WooCommerce add discount to cart programmatically value.

discount value

Save the discount campaign. Let’s try the discount from the front end.

Add the specific products to the cart, and it will add a 20% discount to the products.

woocommerce add discount to cart programmatically

Creating a Conditional Discount Using a Plugin

In our last WooCommerce add discount to cart programmatically example, we will create a multi-conditional discount.

Let’s say you want to offer a BOGO deal where you give away a free t-shirt to your loyal customers with a rich store purchase history. For example, a free t-shirt for those who have spent a minimum of $500 overall at your store on their next purchase.

Create a new discount campaign and set your campaign name. Select BOGO from the Discount Intention field.

BOGO campaign

We will select All Products for this one.

select all products

From the BOGO tab, select the Products type.

BOGO product

In the BOGO Rules tab, first, select the quantity customers need to add to the cart to avail of the discount. Then, search for and select the product you want to offer for free.

select product

Next, select the quantity you want to offer for free. After that, select Free as the discount type.

BOGO set

Next up, adding conditions to the WooCommerce add discount to cart programmatically campaign. Click the Add Condition button.

BOGO rules

Scroll down the filters and find the option – Total Amount Spent By The Customer.

Add condition

Select Equal and input the minimum spent value.

BOGO deal woocommerce add discount to cart programmatically

Save the campaign. Now, any loyal returning customer who has spent a total of $500 in your store will enjoy a free t-shirt on their next purchase.

Why Do You Need to Create Automatic Discounts in WooCommerce

There are several compelling reasons why you might want to create automatic discounts in WooCommerce:

Effortless Automation

  • Streamlined Promotions: Imagine promotions that run smoothly without the need to manually adjust prices or create individual coupons for each offer. Programmatic discounts allow you to define the rules and have discounts automatically applied at checkout, saving you a significant amount of time and effort.
  • Recurring Discounts: Do you offer regular sales or have special discounts for specific customer groups (e.g., loyalty programs)? Automatic discounts eliminate the need to manually update prices or coupons every time the promotion rolls around. Set it up once and let it run on autopilot.

Enhanced Customer Experience

  • Frictionless Discounts: Customers don’t need to search for or fumble with coupon codes. Discounts are automatically applied based on the pre-defined conditions, creating a smoother and more enjoyable checkout experience.
  • Targeted Promotions: Programmatic discounts allow you to create targeted promotions based on specific criteria like cart total, product categories, or even user roles. This allows you to personalize the shopping experience and incentivize specific purchases.

Strategic Marketing & Sales

  • Conditional Discounts: Automatically offer discounts based on specific criteria. This can be a powerful tool to encourage customers to spend more (e.g., discount for exceeding a certain cart total) or clear out slow-moving inventory (e.g., discount on specific product categories).
  • Upselling & Cross-selling: Create automatic discounts that incentivize customers to add specific products to their cart. For example, offer a discount on a complementary product when a customer adds a particular item.

Additional Considerations

  • Flexibility: Programmatic discounts offer a high degree of flexibility compared to traditional coupons. You can create complex discount structures based on various conditions.
  • Data-Driven Marketing: By analyzing customer behavior and purchase patterns, you can create targeted automatic discounts that are more likely to resonate with your audience and drive sales.

Wrap up

WooCommerce add discount to cart programmatically can significantly boost your conversions and store growth. It can bring new customers as well as satisfy returning customers.

However, it’s important to remember that automatic discounts aren’t a one-size-fits-all solution. They may not be suitable for every promotion and may eat your profits if not done with the right strategies.

Therefore, you need to choose the right method based on your needs and always prioritize testing and analyzing the effectiveness of your discount strategies.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

6,004,101+ Downloads. 617+ plus 5-star ratings. Promote products on any platform you want.