代码之家  ›  专栏  ›  技术社区  ›  Devner

Woocommerce:以编程方式从购物车中删除已申请的特定费用

  •  0
  • Devner  · 技术社区  · 5 年前

    我已通过以下方式向WooCommerce购物车申请了特定费用:

    WC()->cart->add_fee( __( "Delivery Fee"), 50);
    

    上面的代码所做的是,除了小计和运费外,它还将运费加到总价中,并正确显示总价。

    我现在想以编程方式删除申请的费用,但我无法这样做。

    我试过了,但不起作用:

    WC()->cart->remove_fees( __( "Delivery Fee"));
    

    这是我的完整代码:

    add_action( 'woocommerce_before_cart', 'custom_fees' );
    function custom_fees() {
        // Add Fees - This WORKS
        WC()->cart->add_fee( __( "Delivery Fee"), 50);
    
        // Remove Fees - This DOES NOT WORK
        WC()->cart->remove_fees( __( "Delivery Fee"));
    }
    

    我如何以编程方式删除申请的费用,而无需清空购物车?

    0 回复  |  直到 5 年前
        1
  •  7
  •   Reigel Gallarde    5 年前

    根据您的需求,这里有一个解决方案:

    add_action( 'woocommerce_before_calculate_totals', 'custom_fees' );
    function custom_fees() {
        // Add Fees - This WORKS
        WC()->cart->add_fee( __( "Delivery Fee"), 50); // gets removed
        WC()->cart->add_fee( __( "Delivery Fee2"), 150); // will not be removed.
    
        $fees = WC()->cart->get_fees();
        foreach ($fees as $key => $fee) {
            if($fees[$key]->name === __( "Delivery Fee")) {
                unset($fees[$key]);
            }
        }
        WC()->cart->fees_api()->set_fees($fees);
    }