2

在 Woocommerce 中,如果购物车项目具有分配给相关产品的特定运输类别,我会尝试添加运费。我希望将此运费乘以购物车商品数量...</p>

当将产品添加到购物车并且数量增加并且额外的运费也增加时,我可以使用此功能。但是,如果我添加其他具有相同运输等级的产品并增加数量,则额外费用不会增加。

这是我的代码:

// Add additional fees based on shipping class
function woocommerce_fee_based_on_shipping_class( $cart_object ) {

    global $woocommerce;

    // Setup an array of shipping classes which correspond to those created in Woocommerce
    $shippingclass_dry_ice_array = array( 'dry-ice-shipping' );
    $dry_ice_shipping_fee = 70;

    // then we loop through the cart, checking the shipping classes
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $shipping_class = get_the_terms( $value['product_id'], 'product_shipping_class' );
        $quantity = $value['quantity'];

        if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, $shippingclass_dry_ice_array ) ) {
            $woocommerce->cart->add_fee( __('Dry Ice Shipping Fee', 'woocommerce'), $quantity * $dry_ice_shipping_fee ); // each of these adds the appropriate fee
        }
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'woocommerce_fee_based_on_shipping_class' ); // make it all happen when Woocommerce tallies up the fees

我怎样才能使它也适用于其他购物车项目?

4

2 回答 2

3

您的代码有点过时,并且存在一些错误。要根据产品运输类别和购物车商品数量添加费用,请使用以下命令:

// Add a fee based on shipping class and cart item quantity
add_action( 'woocommerce_cart_calculate_fees', 'shipping_class_and_item_quantity_fee', 10, 1 ); 
function shipping_class_and_item_quantity_fee( $cart ) {

    ## -------------- YOUR SETTINGS BELOW ------------ ##
    $shipping_class = 'dry-ice-shipping'; // Targeted Shipping class slug
    $base_fee_rate  = 70; // Base rate for the fee
    ## ----------------------------------------------- ##

    $total_quantity = 0; // Initializing

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ) {
        // Get the instance of the WC_Product Object
        $product = $cart_item['data'];

        // Check for product shipping class
        if( $product->get_shipping_class() == $shipping_class ) {
            $total_quantity += $cart_item['quantity']; // Add item quantity
        }
    }

    if ( $total_quantity > 0 ) {
        $fee_text   = __('Dry Ice Shipping Fee', 'woocommerce');
        $fee_amount = $base_fee_rate * $total_quantity; // Calculate fee amount

        // Add the fee
        $cart->add_fee( $fee_text, $fee_amount );
    }
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

于 2019-03-01T15:59:28.067 回答
0

如果购物车中有一个运输类别,则不应收取任何费用,但如果有多个运输类别,则应额外收取 1 欧元的手续费,并且每增加一个运输类别。

情况 1:将配送类别(仓库 1)的产品添加到购物车 = 无额外费用

情况 2:将具有运输类别(仓库 1)的产品添加到购物车,将具有另一个运输类别(仓库 2)的产品添加到购物车 = 1x 已添加到购物车的手续费 小计:产品 2x - 10 欧元运费 - 免费手续费 1x - 1 欧元总计- 11 欧元

情况 3:将运输类别(仓库 1)的产品添加到购物车,将运输类别(仓库 2)的产品添加到购物车,将运输类别(仓库 3)的产品添加到购物车 = 2x 处理费添加到购物车 小计:产品 3x - 15 欧元运费 - 免手续费 2x - 1 欧元 总计 - 12 欧元

于 2021-12-20T19:55:29.360 回答