如何根据woocommerce的权重调整价格?

时间:2019-07-15 21:19:19

标签: wordpress woocommerce

我想在我的商店上使用WordPress上的Woocommerce,但客户应该可以按单位或重量购买产品。

如果购买了X个单位,我们必须测量购买的实际重量(在订购和包装订单期间获得),并相应地调整价格。

在Woocommerce上有简单的方法吗?

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码段进行修改-

function adjust_price_based_on_weight( $cart_object ) {
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {              
        $_product   = $cart_item['data'];
        $product_id = $cart_item['product_id'];
        $quantity = $cart_item['quantity'];

        $product_price = floatval( $_product->get_price() ); // Actual product price
        // Do your calculation based on product quantity and weight
        // for example suppose product per unit weight 2 kgs and add to cart number of unit is 3.
        $product_unit_weights = $quantity * 2; // where 2kg/per unit and $quantity is 3
        if( $product_unit_weights > 5 ) { // if units weights is greter than 5 kgs additional cost 10.
            $additionalPrice = 10;
            $_product->set_price( $product_price + $additionalPrice );
        }   
    }
}
add_action( 'woocommerce_before_calculate_totals', 'adjust_price_based_on_weight', 99 );