以编程方式从购物车中删除应用的特定费用

Dev*_*ner 5 php wordpress woocommerce

我已通过以下方式向我的 WooCommerce 购物车收取特定费用:

WC()->cart->add_fee( __( "Delivery Fee"), 50);
Run Code Online (Sandbox Code Playgroud)

上面代码的作用是,除了小计和运费之外,还将运费添加到总计中并正确显示总计。

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

我尝试过这个,但它不起作用:

WC()->cart->remove_fees( __( "Delivery Fee"));
Run Code Online (Sandbox Code Playgroud)

这是我的完整代码:

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"));
}
Run Code Online (Sandbox Code Playgroud)

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

Rei*_*gel 10

取决于您的需要,这是一种解决方案:

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);
}
Run Code Online (Sandbox Code Playgroud)