5

I need set a discount manually without using coupons.

I have checked the Woocommerce source in Github and I see that it uses "set_discount_total" functions, but it does not work.

I have tried WC()->cart->set_discount_total(15) and $order->set_discount_total(15); but nothing.

This is my code:

<?php
function letsgo_order_total($order_id, $posted_data, $order) {
    $order = wc_get_order( $order_id );
    $order->set_discount_total(50);
}
add_action('woocommerce_checkout_order_processed','letsgo_order_total',10,3);
?>

Actually I have discovered a way to do it, it works but I do not like the code:

<?php
$cart_discount = 50;
$discount = (double)get_post_meta($order_id,'_cart_discount',true);
update_post_meta($order_id,'_cart_discount',$cart_discount + $discount);
?>
Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
Alexander
  • 149
  • 1
  • 3
  • 13
  • If you just want to be able to give "coupon-like" discounts to people visiting a landing page *without* having a coupon field on your checkout form, you might look at the [URL Coupons](https://woocommerce.com/products/url-coupons/) plugin. – s3cur3 Dec 31 '19 at 14:59

1 Answers1

2

This is a code snippet from this answer which I have used and works well. How to add discount to cart total?

 // Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');

/**
 * Add custom fee if more than three article
 * @param WC_Cart $cart
 */
function add_custom_fees( WC_Cart $cart ){
    if( $cart->cart_contents_count < 3 ){
        return;
    }

    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.1;
    $cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}
Katie
  • 331
  • 2
  • 6