【问题标题】:WooCommerce: How to duplicate shipping cost for backorder products at checkout?WooCommerce:如何在结帐时复制延期交货产品的运费?
【发布时间】:2021-04-08 17:25:44
【问题描述】:

您好,我需要为缺货的产品添加额外的运费。 IE。如果在结帐时用户有 3 件产品 1 有库存、两个延期交货且所选的运输方式成本为 5 美元,则产生 10 美元的额外费用(每个延期交货 5 美元)。

总之我需要:

1 - Get the cart information and identify how many backorders are;
2 - Create an extra cost (shipping cost x backorders number);
3 - Update the extra cost if shipping method is changed;

我不期望代码中的解决方案,但我想知道我可以使用哪些钩子来实现上述目标。

【问题讨论】:

  • 你试过什么?你到底卡在哪里了?
  • 集思广益最好使用的钩子。

标签: woocommerce hook-woocommerce shipping


【解决方案1】:

代码如下。如何为延期交货的产品增加额外的运费。

// Add a extra shipping fee to each backordered product
add_action('woocommerce_cart_calculate_fees', 'add_backorder_shipping_fee', 20, 1);
function add_backorder_shipping_fee($cart)
{
    if (is_admin() && !defined('DOING_AJAX'))
        return;

    $backorderNumber = 0;    
    // Loop through the cart items (added products).
    foreach (WC()->cart->get_cart() as $cart_item) {
        // Product Info
        $product = $cart_item['data'];
        // Quantity of product in cart (being purchased).
        $buyingQuantity = $cart_item['quantity'];
        if (!empty($product)) {
            // Calculate if product quantity in cart is more than stock, returns negative if so.
            $isBuyingMoreThanStock = $product->stock_quantity - $buyingQuantity;
            if ($isBuyingMoreThanStock < 0) {
                // Calculate the number of items are being backordered.
                $backorderNumber = $backorderNumber + ($isBuyingMoreThanStock * -1);   
            }
        }
    }
    // Get the shipping cost.
    $totalShippingCost = WC()->cart->get_shipping_total();
    // Calculate and apply the above shipping cost to each backordered item.
    $extraShippingFee = $backorderNumber * $totalShippingCost;
    // Create the fee.
    $cart->add_fee(__('Backorder Extra Shipping Fee (' . $backorderNumber . ')', 'woocommerce'), $extraShippingFee);

}

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 2020-07-31
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    相关资源
    最近更新 更多