Programmatically Applying Coupons in WooCommerce Based on Cart Weight
Automating discount logic based on dynamic cart attributes, such as total weight, is a common requirement for logistics-heavy e-commerce stores. While WooCommerce provides robust APIs for managing coupons, applying them programmatically requires careful handling of the cart object and hook system to avoid unexpected side effects or infinite loops.
The core mechanism lies within the WC_Cart class. Specifically, you can utilize the add_discount() method to attach a coupon code and remove_coupons() to detach it. These methods accept a single string representing the coupon code. In your specific use case, where a 10% discount is triggered when cart weight exceeds 100 lbs, you would target a pre-created coupon code (e.g., '99' or 'HEAVY_LIFT') rather than trying to calculate the percentage directly via API calls.
A critical distinction exists between applying a discount manually versus programmatically. The add_discount() method returns a boolean value: true if the discount was successfully added, and false if it failed (often because the coupon is already active or invalid). Ignoring this return value can lead to silent failures where the user sees no change in their total, even though your logic dictated a discount should be applied. You must always check this boolean result before attempting to display messages to the customer.
To implement this within functions.php, you need to hook into the cart lifecycle. The most appropriate location for applying or removing these dynamic discounts is the woocommerce_before_cart_table action. This hook fires after the cart contents are rendered but before the totals are calculated, ensuring that any logic modifying the cart state happens at the right time in the rendering cycle.
However, simply adding a function to apply the coupon isn't enough if the condition changes mid-session. If a customer adds items and drops below the 100 lb threshold, or removes items and goes over it, the discount needs to toggle accordingly. This requires two distinct handlers: one to enforce the discount when weight > 100, and another to strip it when weight <= 100.
Consider the following implementation pattern based on a working solution that integrates with existing cart modifications in cart.php:
// Apply discount when weight exceeds 100 lbs
add_action('woocommerce_before_cart_table', 'apply_heavy_lift_discount');
function apply_heavy_lift_discount() {
global $woocommerce;
// Ensure $total_weight is available from the cart object or passed context
if ( !isset($total_weight) || empty($total_weight) ) {
return;
}
if ($total_weight > 100) {
$coupon_code = '999'; // Replace with your actual coupon code
// Attempt to add the discount
if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) {
// If it returns false, the coupon might already be applied or is invalid.
// Only show messages if we explicitly want to handle errors here.
$woocommerce->show_messages();
} else {
echo '<div class="woocommerce_message"><strong>10% Discount Applied!</strong></div>';
}
}
}
// Remove discount when weight is 100 lbs or less
add_action('woocommerce_before_cart_table', 'remove_heavy_lift_discount');
function remove_heavy_lift_discount() {
global $woocommerce;
if (isset($total_weight) && $total_weight <= 100) {
$coupon_code = '999';
// Check current applied coupons first to ensure safety
$applied_coupons = $woocommerce->cart->get_applied_coupons();
// Remove the specific coupon if it exists
if (!$woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code))) {
$woocommerce->show_messages();
}
// Crucial: Recalculate totals immediately after removing a discount
$woocommerce->cart->calculate_totals();
}
}
There are several pitfalls to watch out for when using this approach. First, relying on global variables like $total_weight can be fragile if they aren't properly initialized in every cart context. It is often safer to access the weight directly via $woocommerce->cart->cart_contents_weight if the variable isn't globally exposed in your theme's cart.php.
Second, calling calculate_totals() after modifying discounts is non-negotiable. WooCommerce caches totals; without recalculating, the UI will display the old price until the page refreshes or an AJAX call forces a recalculation. Third, be mindful of the order of operations. If you are using a plugin that manages coupons automatically, your custom logic might conflict with it. In such cases, wrapping your logic in apply_filters allows other developers to intercept or modify the behavior without overwriting their code.
This pattern provides a clean, maintainable way to handle conditional discounts without requiring complex AJAX calls or modifying core files permanently. By leveraging the standard cart actions and the WC_Cart API, you ensure compatibility across different WooCommerce versions while keeping your logic isolated within functions.php.