Apply a discount on the cart content total excluding taxes in WooCommerce

一世执手 提交于 2019-11-29 08:40:46

UPDATE: Using a negative fee is not the best way and not recommended by Woocommerce.

Note that the taxes will be always applied.

Try instead:
- Cart item quantity progressive percentage discount in Woocommerce 3
- Cart item discount based on quantity in Woocommerce 3
- Apply automatically a coupon based on specific cart items count in Woocommerce

There is a much more simpler way, is to use a negative fee, so a discount. It use the WC_Cart method add_fee() where you can disable tax:

add_action( 'woocommerce_cart_calculate_fees','new_customers_discount', 10, 1 );
function new_customers_discount( $wc_cart ) {
    if ( is_admin() && ! defined('DOING_AJAX') ) return; // We exit

    // Only for logged in users
    if ( ! is_user_logged_in() ) return; // We exit

    // Only for new customers without orders
    if ( wc_get_customer_order_count( get_current_user_id() ) != 0 ) return;  // We exit

    // discount percentage
    $percent = 5;

    // Calculation
    $discount = $wc_cart->cart_contents_total * $percent / 100;

    $wc_cart->add_fee( __( 'Discount', 'woocommerce')." ($percent%)", -$discount );
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and working. you will get something like that:

As you can see the discount is maid on the cart content total excl. Tax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!