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

时间:2019-03-01 11:11:09

标签: wordpress woocommerce product shipping fee

在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

我如何也可以将其用于其他购物车?

1 个答案:

答案 0 :(得分: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文件中。经过测试,可以正常工作。