WooCommerce

WooCommerce添加附加费surcharge(2021)

WooCommerce的Fees API允许我们向购物车和结算页面添加附加费(surcharge),可以根据不同国家,用户购买的产品数量、产品总价等等来设定费用。今天介绍以下WooCommerce添加附加费的方法。

WooCommerce添加附加费代码

add_action( 'woocommerce_cart_calculate_fees','sola_wc_custom_surcharge' );
function sola_wc_custom_surcharge() {
    global $woocommerce;

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


    // Filter fees by country
    $allowed_country = array('US');

    if ( ! in_array( $woocommerce->customer->get_shipping_country(), $allowed_country ) ){
        return;
    }


    //Add a 1% surcharge to your cart / checkout
    $percentage     = 0.01;
    $cart_total     = $woocommerce->cart->cart_contents_total;
    $shipping_total = $woocommerce->cart->shipping_total;
    $surcharge      = ( $cart_total + $shipping_total ) * $percentage;

    $woocommerce->cart->add_fee( 'Surcharge', $surcharge, false, '' );

}

如果你选择的国家是美国,就能在购物车或者结算页面看到这笔附加费。

WooCommerce添加附加费代码

WC_Cart::add_fee() 

该方法的参数如下:

  • $name – 附加费的独有ID,不要重复,相同ID的多比费用不能叠加
  • $amount – 附加费的价格,不能是复数
  • $taxable – 附加费是否需要收税,默认否
  • $tax_class – 如果$taxable为true,指定tax class

参考文章:Add a surcharge to cart and checkout – uses fees API