Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a discount in WooCommerce without a coupon

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);
?>
like image 612
Alexander Avatar asked Oct 28 '22 18:10

Alexander


1 Answers

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);
}
like image 183
Katie Avatar answered Jan 02 '23 19:01

Katie