首页 文章

自定义WooCommerce费用在结账时消失

提问于
浏览
2

我在 woocommerce_cart_calculate_fees 上添加了自定义费用:

add_action('woocommerce_cart_calculate_fees', 'delivery_surcharge');
function delivery_surcharge() {
    global $woocommerce;
    // ...
    $woocommerce->cart->add_fee('Delivery fee', $fee, false, '');
}

但是,一旦用户点击结帐,费用就会被删除,而不会计入总额 .

通过执行以下检查,我已经确认在调用 woocommerce_checkout_process 时尚未删除费用:

add_action('woocommerce_checkout_process', 'checkout_validator');
function checkout_validator() {
    global $woocommerce;
    wc_add_notice($woocommerce->cart->get_total(), 'error');
}

这给了我一个结帐错误,显示包括定制费用的总额 . 然而,当我第二次点击结账时,费用已经消失,需要第二次再次呼叫才能重新出现 .

此外,在 woocommerce_checkout_process 中签入时, WC_Cart::get_fees() 返回的数组中也会显示费用 .

Edit: 请参阅更新5 .

相关问题

“Woocommerce won't add my custom fee to the cart total”—Related but with no useful answer

更新

Update 1: 我在 WC_Checkout::create_order() 添加了以下内容:

251 // Store fees
+ 252 error_log(print_r(WC()->cart->get_fees(), true));
  253 foreach ( WC()->cart->get_fees() as $fee_key => $fee ) {

输出空数组意味着在结账处理和订单创建之间的某个时间删除费用 .

Update 2: 我执行了类似上面的另一个调试检查,这次添加到 WC_Shortcode_Checkout::checkout()

230 // Check cart has contents
  231 if ( WC()->cart->is_empty() ) {
  232     return;
  233 }
+ 234   
+ 235 error_log(print_r(WC()->cart->get_fees(), true));
  236
  237 // Check cart contents for errors
  238 do_action( 'woocommerce_check_cart_items' );

结果又是一个空数组 .

Update 3: 最后,有些进展!我再次执行了类似的检查,这次是 WC_Checkout::process_checkout() ,由 WC_Ajax::checkout() 调用:

359 if ( ! defined( 'WOOCOMMERCE_CHECKOUT' ) ) {
  360     define( 'WOOCOMMERCE_CHECKOUT', true );
  361 }
+ 362
+ 363 error_log(print_r(WC()->cart->get_fees(), true));
  364
  365 // Prevent timeout
  366 @set_time_limit(0);

费用实际上出现在 error_log

[12-Aug-2016 13:45:24 UTC] Array
(
    [0] => stdClass Object
        (
            [id] => delivery-fee
            [name] => Delivery fee
            [amount] => 4
            [tax_class] => 
            [taxable] => 
            [tax] => 0
            [tax_data] => Array
                (
                )

        )

)

我将继续跟踪此功能,直到我(希望)发现费用未设置的确切位置 .

Update 4: 我已经设法追踪 WC_Cart::calculate_totals() 调用 WC_Cart::calculate_totals() 后某处的费用未设置 . 进一步调查 .

Update 5: 我完全找到了这个问题 . 显然 WC_Cart::calculate_totals() 调用 WC_Cart::reset() ,取消所有费用 . 我不确定这是如何运作的,但不知何故,以前,费用在 WC_Cart::reset() 的电话中幸免于难 . 此时我不确定这是否是我的实现或WooCommerce本身的错误 .

2 回答

  • 0

    我自己整理了一下 . 事实证明,在我特定的,过时的WooCommerce版本中没有正确调用 woocommerce_cart_calculate_fees 是一个问题 . 更新解决了这个问题 .

  • 0

    您可以使用此代码禁用重置费用的操作 .

    remove_action('woocommerce_cart_reset', array(WC()->cart->fees_api(), 'remove_all_fees'));
    

相关问题