php购物车修改单价,php-根据Woocommerce中特定产品属性值更改购物车项目价格

我正在尝试使用以下功能更改购物车中的产品价格:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10);

function add_custom_price( $cart_obj ) {

foreach ( $cart_obj->get_cart() as $key => $value ) {

$item_data = $value['data'];

$price0 = $item_data->get_attributes('per_one_price');

$price = (int) $price0;

$value['data']->set_price( $num_int );

}

}

但是,对于我设置为per_one_price属性的产品属性值的任何数字,我都得到购物车价格中的数字1.

解决方法:

Update – There is 2 little mistakes:

Replace get_attributes() by get_attribute() (singular).

Replace 'per_one_price' by 'Per one price' (or 'per-one-price' as blank spaces are replaced by dashes)

因此,请尝试以下操作:

add_action( 'woocommerce_before_calculate_totals', 'set_custom_item_price', 20, 1 );

function set_custom_item_price( $cart ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) )

return;

if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )

return;

// Loop through cart items

foreach ( $cart->get_cart() as $cart_item ) {

// get attibute value

$new_price = $cart_item['data']->get_attribute('per-one-price');

if( ! empty( $new_price ) ){

// Set the new price

$cart_item['data']->set_price( $new_price );

}

}

}

代码进入您的活动子主题(或活动主题)的function.php文件中.测试和工作.

创建“每一个价格”产品属性:

T47Rv.png

产品价格设置视图:

RGwFG.png

在产品中设置的产品属性及其值:

9JPdD.png

该产品的购物车页面视图:

9beY9.png

标签:woocommerce,product,price,custom-taxonomy,php

来源: https://codeday.me/bug/20191108/2009042.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值