Apply a coupon programmatically in Woocommerce
Asked Answered
W

3

41

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.

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.

EDIT: Partial code removed, completed code included in the solution below.


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();
    }
}
Windpollinated answered 1/4, 2013 at 13:46 Comment(0)
S
40

First, create a discount coupon (via http://docs.woothemes.com/document/create-a-coupon-programatically/):

$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();

That last function returns a BOOL value: TRUE if the discount was successful, FALSE if it fails for any one of a variety of reasons.

Sunburn answered 2/4, 2013 at 2:43 Comment(11)
Since I already have a coupon in the backend: "999" I only added the code you provided to apply the coupon. However, when I go to the woocommerce cart page I am now getting the error: Call to a member function add_discount() on a non-object in [path to…] functions.php on line 65 [the if statement with add_discount]. I've updated the code in my original post to show you what it looks like.Windpollinated
Try adding global $woocommerce; along with your $total_weight line.Sunburn
Thank you, that worked! So now I am able to successfully apply the discount but now I'm noticing another issue… If the user removes some cart items and the cart goes back to 100 lbs or less then the discount is still there. I'm looking for a way to remove the discount if the cart no longer meets the condition so users won't be able to exploit this coupon. I would expect there to be a remove_discount function that works the opposite way of add_discount but I haven't been able to find one in the Woocommerce API docs: docs.woothemes.com/wc-apidocsWindpollinated
I noticed that there's a way to remove the discount manually by clicking a link: "Order Discount [Remove]" on the cart page. I'm looking into ways to automatically trigger this link with javascript (although not ideal) if the weight goes back to 100 lbs or less. I am able to execute raw javascript from functions.php but am unable to use jquery for some reason (even though jquery 1.8.3 is clearly being loaded on the cart page). I made an attempt to to target the link and use the click function (updated above), I'm not quite there yet and even if it does work will only be available in IE8+ :(Windpollinated
Let me know if it makes more sense to just post a new question for the "remove_discount" function and the javascript issues since you technically answered my original question.Windpollinated
Excellent. I think the way to go here would be to remove the code from the $woocommerce->cart->get_applied_coupons(); array, then apply $woocommerce->cart->calculate_totals();.Sunburn
Oh, and hook that into a similar action as your one above to catch the weight dropping below 100.Sunburn
Hi could you please check my question also wordpress.stackexchange.com/questions/215238/…Dichotomize
I have and question, It's posible apply a coupon directly to the order without going through the cart?Subchloride
please check this question also #49505556Refresher
can someone explains why the first code @Sunburn provided create more than one coupon code? i expect it to create only one. (was added to functions.php)Elora
P
8

I used this solution, but it contains a bug as the OP wrote it. If the user skips previewing the cart and goes straight to the checkout form, it does not apply the coupon. Here was my solution.

// Independence day 2013 coupon auto add
// Add coupon when user views cart before checkout (shipping calculation page).
add_action('woocommerce_before_cart_table', 'add_independence_day_2013_coupon_automatically');

// Add coupon when user views checkout page (would not be added otherwise, unless user views cart first).
add_action('woocommerce_before_checkout_form', 'add_independence_day_2013_coupon_automatically');

// Check if php function exists.  If it doesn't, create it.
if (!function_exists('add_independence_day_2013_coupon_automatically')) {

    function add_independence_day_2013_coupon_automatically() {

        global $woocommerce;
        $coupon_code = 'independencedaysale';
        $bc_coupon_start_date = '2013-06-30 17:00:00';
        $bc_coupon_end_date = '2013-07-08 06:59:59';

        // Only apply coupon between 12:00am on 7/1/2013 and 11:59pm on 7/7/2013 PST.
        if ((time() >= strtotime($bc_coupon_start_date)) &&
            (time() <= strtotime($bc_coupon_end_date))) {

            // If coupon has been already been added remove it.
            if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code))) {

                if (!$woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code))) {

                    $woocommerce->show_messages();

                }

            }

            // Add coupon
            if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) {

                $woocommerce->show_messages();

            } else {

                $woocommerce->clear_messages();
                $woocommerce->add_message('Independence day sale coupon (10%) automatically applied');
                $woocommerce->show_messages();

            }

            // Manually recalculate totals.  If you do not do this, a refresh is required before user will see updated totals when discount is removed.
            $woocommerce->cart->calculate_totals();

        } else {

            // Coupon is no longer valid, based on date.  Remove it.
            if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code))) {

                if ($woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code))) {

                    $woocommerce->show_messages();

                }

                // Manually recalculate totals.  If you do not do this, a refresh is required before user will see updated totals when discount is removed.
                $woocommerce->cart->calculate_totals();

            }

        }

    }

}
Provincetown answered 5/7, 2013 at 21:41 Comment(0)
G
7

2017 / 2019 since Woocommerce 3

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.

The code:

add_action('woocommerce_before_calculate_totals', 'discount_based_on_weight_threshold');
function discount_based_on_weight_threshold( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Your settings
    $coupon_code      = 'onweight10'; // Coupon code
    $weight_threshold = 100; // Total weight threshold

    // Initializing variables
    $total_weight     = $cart->get_cart_contents_weight();
    $applied_coupons  = $cart->get_applied_coupons();
    $coupon_code      = sanitize_text_field( $coupon_code );

    // Applying coupon
    if( ! in_array($coupon_code, $applied_coupons) && $total_weight >= $weight_threshold ){
        $cart->apply_coupon( $coupon_code );
        wc_clear_notices();
        wc_add_notice( sprintf(
            __("Your order is over %s so a %s Discount has been Applied! Your total order weight is %s.", "woocommerce"),
            wc_format_weight( $weight_threshold ), '10%', '<strong>' . wc_format_weight( $total_weight ) . '</strong>'
        ), "notice");
    }
    // Removing coupon
    elseif( in_array($coupon_code, $applied_coupons) && $total_weight < $weight_threshold ){
        $cart->remove_coupon( $coupon_code );
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

enter image description here

Grecoroman answered 26/12, 2018 at 9:27 Comment(1)
Hello @Grecoroman i have a question. if user have 4-5 coupons. i want it to apply all automatically in the checkout/cart pageFluster

© 2022 - 2024 — McMap. All rights reserved.