添加 Woocommerce 购物车费用不会在结帐时持续存在

Add a Woocommerce cart fee does not persist in checkout

我使用 add_fee 方法收取我的购物车价格。它有效并且没问题,但是当我单击结帐按钮并转到结帐页面或刷新页面时,新价格消失而旧价格在那里。如何在购物车中保存我的价格?

function woo_add_cart_fee($cart_obj) {
    global $woocommerce;

    $count = $_POST['qa'];

    $extra_shipping_cost = 0;
    //Loop through the cart to find out the extra costs
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
        //Get the product info
        $_product = $values['data'];

        //Adding together the extra costs
        $extra_shipping_cost = $extra_shipping_cost + $_product->price;
    }

    $extra_shipping_cost = $extra_shipping_cost * $count;
    //Lets check if we actually have a fee, then add it
        if ($extra_shipping_cost) {
            $woocommerce->cart->add_fee( __('count', 'woocommerce'),   $extra_shipping_cost );
        }
}
add_action( 'woocommerce_before_calculate_totals', 'woo_add_cart_fee');

您需要改用 woocommerce_cart_calculate_fees 挂钩。我还重新访问了您的代码,因为您需要存储 $_POST['qa']; 值以使费用持久化:

add_action( 'woocommerce_cart_calculate_fees', 'cart_custom_fee', 20, 1 );
function cart_custom_fee( $cart_obj ) {

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

    $count = $_POST['qa'];

    $extra_shipping_cost = 0;

    // Loop through the cart items to find out the extra costs
    foreach ( $cart_obj->get_cart() as $cart_item ) {

        //Adding together the extra costs
        $extra_shipping_cost = $extra_shipping_cost + $cart_item['data']->price;
    }

    $extra_shipping_cost = $extra_shipping_cost * $count;

    //Lets check if we actually have a fee, then add it
    if ( $extra_shipping_cost != 0 ) {
        $cart_obj->add_fee( __('count', 'woocommerce'),   $extra_shipping_cost );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。

现在应该可以正常工作了。