根据运输类别和物品数量添加Woocommerce费用

问题描述 投票:2回答:1

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

当产品被添加到购物车并且数量增加并且额外的运输费用也增加时,我有这个工作。但是,如果我添加具有相同运输等级的其他产品并增加数量,则额外费用不会增加。

这是我的代码:

// 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

如何使其适用于其他购物车项目?

wordpress woocommerce product shipping fee
1个回答
1
投票

你的代码有点过时,有一些错误。要根据产品运输类别和购物车项目数量添加费用,请使用以下内容:

// 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文件中。经过测试和工作。

© www.soinside.com 2019 - 2024. All rights reserved.