Woocommerce根据数量和变化改变价格



我目前正在为客户使用 woocommerce 创建我的第一个网站,他们要求我按变化和数量提高价格,但我不确定该怎么做。以下是他们要求的示例:

产品类型:石灰石

变化:

  • 产品尺寸:
    • 10公斤袋
    • 20公斤袋
    • 40公斤袋装
  • 数量:
    • 1-20

TL;博士 如果客户想要多个 10

公斤的袋子,价格一次增加 36 英镑,如果他们想要多个 20 公斤的袋子,价格一次增加 30 英镑,如果他们想要多个 40 公斤的袋子,价格每次都会翻倍。到目前为止,我已经使用了woocommerce变体和属性,但现在需要修改具有3x20变体的所有变体,所有这些变体都需要不同的价格,如果可以执行以下操作,则更容易更改:

if ($productsize === '10kg') {
$quantity = 2; //get quantity from textbox $_POST
$initial_price = 36; //get inital price from woocommerce global variable

$total_price = $inital_price * $quantity;
update_price($total_price); //a function to update the price in woocommerce when adding to cart

}

显然,上面的代码不使用任何 woocommerce 变量,但是仅对 3 个变体执行此操作比在我们的网站上有 60 个>60 个产品上手动输入 60 个变体更容易。

我不知道你是否需要它了,但是尝试一下

add_action( 'woocommerce_before_calculate_totals', 'IG_recalculate_price',5,1 );
function IG_recalculate_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$quantity = 0;

foreach ( $cart_object->get_cart() as $key => $value ) {
// count q.ty
$quantity += $value['quantity'];
// delta q.ty  
if( $quantity > 24 ) {
// get price by custom field but you can use a simple var
$newprice = get_post_meta( $value['data']->get_id(), 'custom_field2', true);
$value['data']->set_price( $newprice );
// reset q.ty for check every item in the cart
$quantity = 0;
}else{
$newprice = get_post_meta( $value['data']->get_id(), 'custom_field', true);
$value['data']->set_price( $newprice );
$quantity = 0;
}
}
}

最新更新