Apply a coupon programmatically in Woocommerce

Asked
Active3 hr before
Viewed126 times

8 Answers

couponprogrammaticallyapply
90%

In Woocommerce I'm trying to find a way to apply a 10% discount to an entire customer's order if the weight in the cart is over 100 lbs. I'm partway to achieving this. For the next step, I'm looking for a way to programmatically apply a coupon code via action/hook through functions.php.,It appears that I can use the function woocommerce_ajax_apply_coupon to do this ( http://docs.woothemes.com/wc-apidocs/function-woocommerce_ajax_apply_coupon.html ) but I am unsure of how to use it., Jobs Programming & related technical career opportunities , Podcast 392: Do polyglots have an edge when it comes to mastering programming...

$coupon_code = 'UNIQUECODE'; // Code - perhaps generate this from the user ID + the order ID
$amount = '10'; // Amount
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product

$coupon = array(
   'post_title' => $coupon_code,
   'post_content' => '',
   'post_status' => 'publish',
   'post_author' => 1,
   'post_type' => 'shop_coupon'
);

$new_coupon_id = wp_insert_post($coupon);

// Add meta
update_post_meta($new_coupon_id, 'discount_type', $discount_type);
update_post_meta($new_coupon_id, 'coupon_amount', $amount);
update_post_meta($new_coupon_id, 'individual_use', 'no');
update_post_meta($new_coupon_id, 'product_ids', '');
update_post_meta($new_coupon_id, 'exclude_product_ids', '');
update_post_meta($new_coupon_id, 'usage_limit', '1');
update_post_meta($new_coupon_id, 'expiry_date', '');
update_post_meta($new_coupon_id, 'apply_before_tax', 'yes');
update_post_meta($new_coupon_id, 'free_shipping', 'no');

Then apply that coupon to your order:

if (!$woocommerce - > cart - > add_discount(sanitize_text_field($coupon_code)))
   $woocommerce - > show_messages();
load more v
88%

Then, in your WordPress dashboard, go to WooCommerce > Coupons to create your coupon link. Depending on the WooCommerce version you use, you may have to go to Marketing > Coupons. Press Add coupon.,Create WooCommerce coupons,In the WordPress dashboard, go to WooCommerce > Coupons and click Add coupon. In some WooCommerce versions, you may find it under Marketing > Coupons. Then enter a coupon code name. You can either type any name you want or use an auto-generated name. In this case, we’ll name it auto_coupon.,For this, we’ll use a free plugin called Advanced Coupons for WooCommerce that you can download from the WordPress repository.

The WC()->cart object is available in front-end pages and it allows you to retrieve all the information related to the cart page. So paste the following script in the functions.php file of your child theme:

add_action('woocommerce_before_cart', 'QuadLayers_apply_coupon');

function QuadLayers_apply_coupon() {
   $coupon_code = 'auto_coupon';
   if (WC() - > cart - > has_discount($coupon_code)) return;
   WC() - > cart - > apply_coupon($coupon_code);
   wc_print_notices();
}
load more v
72%

Create a coupon code that you want to apply once a certain product is added to cart (go to WooCommerce / Coupons / Add New and decide your coupon code. For example “freeweek”, which is the coupon code we will use later in the PHP snippet),I am trying to figure out how to add email notifications when a specific code is applied. In fact, a coupon code will be assigned to sale representative, and we want them to be notified each time their coupon is applied and use. ,Users can manually enter a coupon code, refresh the Cart and see their discount apply… or you can do that automatically (or “programmatically” as we say in the dark web) when a user adds a product to the WooCommerce Cart 🙂,I agree, there is always a way. Is there any way to modify your code, so it applies a coupon to all the products instead of one particular product?

/**
 * @snippet       Apply a Coupon Programmatically if Product @ Cart - WooCommerce 
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WC 4.1
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_action('woocommerce_before_cart', 'bbloomer_apply_matched_coupons');

function bbloomer_apply_matched_coupons() {

   $coupon_code = 'freeweek';

   if (WC() - > cart - > has_discount($coupon_code)) return;

   foreach(WC() - > cart - > get_cart() as $cart_item_key => $cart_item) {

      // this is your product ID
      $autocoupon = array(745);

      if (in_array($cart_item['product_id'], $autocoupon)) {
         WC() - > cart - > apply_coupon($coupon_code);
         wc_print_notices();
      }

   }

}
load more v
65%

Adding the code snippet,Adding the code snippet,Replace UNIQUECODE with a unique coupon code that buyers can use in your shop. Eg: CHRISTMAS30, NewYear20.,Add the discount amount or percentage for the code without currency or percentage symbol.

  1. Adding the code snippet

Copy the following code snippet and paste it at the bottom of the functions.php file. If there is a closing PHP tag (?>) at the bottom, you need to paste the code above the closing PHP tag.

/**
* Create a coupon programatically
*/
$coupon_code = 'UNIQUECODE'; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product


$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon');


$new_coupon_id = wp_insert_post( $coupon );


// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );

/**
 * Create a coupon programatically
 */
$coupon_code = 'UNIQUECODE'; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product
load more v
75%

generate a custom coupon code on the WooCommerce thank you page – this will run when the order process has finished. For this we’ll use the woocommerce_thankyou hook.,Create WooCommerce coupons programmatically,How to add coupons to orders and customers,in the end we’ll show the coupon code on the Thank you page. There are many ways to edit the thank you page. We have a guide on How to customize the WooCommerce thank you page where you can learn more.

Creating the coupon

Creating the coupon object is as simple as creating a post with post type shop_coupon. Here we need to set the coupon code as the post title. We also need to make sure to set the post status to “publish”.

shop_coupon
load more v
40%

We’ll also look at some code that applies a programmatically created coupon to a user’s basket.,We also looked at how to apply a coupon to a user’s basket after creating it programmatically.,Although WooCommerce provides an admin interface to add coupons, sometimes we might want to create a coupon on the fly in code rather than adding one via the admin interface.,We can now use this function to determine if a coupon exists, and only create a new coupon if we do not find one in the database.

The function below will create a coupon

function generate_coupon($coupon_code) {

   $coupon = new WC_Coupon();

   $coupon - > set_code($coupon_code);

   //the coupon discount type can be 'fixed_cart', 'percent' or 'fixed_product', defaults to 'fixed_cart'
   $coupon - > set_discount_type('fixed_cart');

   //the discount amount, defaults to zero
   $coupon - > set_amount(20);

   //the coupon's expiration date defaults to null
   $coupon - > set_date_expires(null);

   //determines if the coupon can only be used by an individual, defaults to false
   $coupon - > set_individual_use(false);

   //the individual prodcuts that the disciunt will apply to, default to an empty array
   $coupon - > set_product_ids(array());

   //the individual products that are excluded from the discount, default to an empty array
   $coupon - > set_excluded_product_ids(array());

   //the times the coupon can be used, defaults to zero
   $coupon - > set_usage_limit(0);

   //the times the coupon can be used per user, defaults to zero
   $coupon - > set_usage_limit_per_user(0);

   //whether the coupon awards free shipping, defaults to false
   $coupon - > set_free_shipping(false);

   //the product categories included in the promotion, defaults to an empty array
   $coupon - > set_product_categories(array());

   //the product categories excluded from the promotion, defaults to an empty array
   $coupon - > set_excluded_product_categories(array());

   //whether sale items are excluded from the coupon, defaults to false
   $coupon - > set_exclude_sale_items(false);

   //the minimum amount of spend required to make the coupon active, defaults to an empty string
   $coupon - > set_minimum_amount('');

   //the maximum amount of spend required to make the coupon active, defaults to an empty string
   $coupon - > set_maximum_amount('');

   //a list of email addresses, the coupon will only be applied if the customer is linked to one of the listed emails, defaults to an empty array
   $coupon - > set_email_restrictions(array());

   //save the coupon
   $coupon - > save();

   return $coupon_code;
}
load more v
22%

The first way to add the coupon code programmatically is by using the wp_insert_post() function which allows you to add or update a WordPress post. So in our case, we are adding a post with post type shop_coupon using this function. To add the meta for the coupons created the update_post_meta() function is used. You need to add the below code to the functions.php file of the child theme or using any code snippets plugin.,After generating the unique string, the next step would be creating the coupon code using a code snippet. We will be discussing 2 ways using which you can create coupon codes programmatically in WooCommerce.,The first step for creating a unique coupon code would be creating a random string for each coupon. That would be created using the below code.,Another way for adding coupon code programmatically is by using the WooCommerce Rest API provided by the plugin itself. WooCommerce has a complete guide provided for the Rest API including Authentication, Fetching Data, Coupons, Orders, etc. but for a reference, below is a small snippet that you can use for coupon code creation.

The first step for creating a unique coupon code would be creating a random string for each coupon. That would be created using the below code.

$characters = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
$char_length = "8";
$random_string = substr(str_shuffle($characters), 0, $char_length);
load more v
60%

The following compact code in one hooked function will add a discount (coupon) based on cart total weight displaying a custom message. If customer changes cart items the code will check cart items removing the discount (coupon) if the cart weight is under the defined weight.,So far I've modified cart.php to get the total weight of all the products in the cart, i've created a coupon that applies the discount (if entered manually) and I've added some code to functions.php to check the weight and display a message to the user.,In Woocommerce I'm trying to find a way to apply a 10% discount to an entire customer's order if the weight in the cart is over 100 lbs. I'm part way to achieving this. For the next step, I'm looking for a way to programmatically apply a coupon code via action/hook through functions.php.,Thanks for the guidance Freney. Here's the working end result which successfully applies the discount coupon when the condition is met and also removes it when it's no longer met:

Thanks for the guidance Freney. Here's the working end result which successfully applies the discount coupon when the condition is met and also removes it when it's no longer met:

/* Mod: 10% Discount for weight greater than 100 lbs 
Works with code added to child theme: woocommerce/cart/cart.php lines 13 - 14: which gets $total_weight of cart:
        global $total_weight;
        $total_weight = $woocommerce->cart->cart_contents_weight;
*/
add_action('woocommerce_before_cart_table', 'discount_when_weight_greater_than_100');
function discount_when_weight_greater_than_100( ) {
    global $woocommerce;
    global $total_weight;
    if( $total_weight > 100 ) {
        $coupon_code = '999';
        if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code ))) {
            $woocommerce->show_messages();
        }
        echo '<div class="woocommerce_message"><strong>Your order is over 100 lbs so a 10% Discount has been Applied!</strong> Your total order weight is <strong>' . $total_weight . '</strong> lbs.</div>';
    }
}

/* Mod: Remove 10% Discount for weight less than or equal to 100 lbs */
add_action('woocommerce_before_cart_table', 'remove_coupon_if_weight_100_or_less');
function remove_coupon_if_weight_100_or_less( ) {
    global $woocommerce;
    global $total_weight;
    if( $total_weight <= 100 ) {
        $coupon_code = '999';
        $woocommerce->cart->get_applied_coupons();
        if (!$woocommerce->cart->remove_coupons( sanitize_text_field( $coupon_code ))) {
            $woocommerce->show_messages();
        }
        $woocommerce->cart->calculate_totals();
    }
}
load more v

Other "coupon-programmatically" queries related to "Apply a coupon programmatically in Woocommerce"