WooCommerce - 制作一组优惠券,为订单添加固定费用

WooCommerce - Make a set of coupons adding a fixed fee to an order

一位客户有一个非常奇怪的要求:他们想要一组优惠券代码来向订单添加费用。这可能吗?

他们试图解决的问题是:

目前,商店提供免费送货到美国本土 48 个州,我已正确配置运费 类 和 table。但是,客户在每日交易网站上出售的优惠券应该会删除免费送货优惠并添加固定运费。

如何实现?

是的,您可以使用该代码段(针对一组优惠券):

function coupon_add_cart_fee( $bookable_total = 0 ) {
    $has_coupon = false;

    // Set here your specials coupons slugs (one by line - last one have no coma)
    $coupon_codes = array (
        'your_coupon_code_slug1',
        'your_coupon_code_slug2',
        'your_coupon_code_slug3' 
    );

    // Set here your fee amount or make fees calculation (see the links in reference)
    $fee = 20;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // checking if that "special" coupon is applied to customer cart
    foreach ($coupon_codes as $coupon_code) {
        if ( WC()->cart->has_discount( $coupon_code ) ) {

            // If yes apply the fee to the cart
            if ( !$has_coupon ) {
                $has_coupon = true;
                break;
            }
        }
    }

    if ( $has_coupon ) {
        WC()->cart->add_fee( 'Fees: ', $fee, false );
    }
}
add_action( 'woocommerce_cart_calculate_fees','coupon_add_cart_fee' );

此代码已经过测试并且有效。 它继续 function.php 您的活动子主题或主题的文件。


TAX OPTIONS with add_fee() method

IMPORTANT: The fact that TAX is working or not with add_fee() method depends first of your tax settings in woocommerce.

Class WC_Cart add_fee() method, adds additional fee to the cart.

add_fee( string $name, float $amount, boolean $taxable = false, string $tax_class = ''  )> <!-- language: lang-css -->

Parameters:
    $name      Unique name for the fee. Multiple fees of the same name cannot be added.
    $amount    Fee amount.
    $taxable   (default: false) Is the fee taxable?
    $tax_class    (default: '') The tax class for the fee if taxable. A blank string is standard tax class.

参考: