php - 如何更改购物车中的可变产品价格还删除删除 Woocommerce 中的特定产品表单购物车
问题描述
在我的网站上,我在购物车中添加了一个可变产品。当时,另一个可变产品也添加到该购物车中,该产品是礼品产品。现在我想将礼品可变产品价格更改为 0,它仅在满足条件时才起作用在购物车中提供礼物的产品。此外,我想通过单击提供礼物的产品来删除两个相同的产品形式。下面我的代码对我不起作用。
add_action( 'woocommerce_before_calculate_totals', 'change_custom_price' );
function change_custom_price( $cart_object ) {
$custom_price = 0; // This will be your custome price
$gift_variation_id = 2046;
foreach ( $cart_object->cart_contents as $value ) {
if ( $value['variation_id'] == $gift_variation_id ) {
$value['data']->price = $custom_price;
}
}
}
解决方案
可以根据此解决方案添加礼品 -在 woocommerce 中买一送一,无需优惠券代码。
您可以将以下内容添加到主题的“functions.php”中,以删除其他产品自动添加的礼品。
function remove_gift_product($cart_item_key) {
global $woocommerce;
$cat_in_cart = false;
$coupon_in_cart = false;
$autocoupon = array( 123411 ); // variation ids of products that offers gifts
$freecoupon = array( 2046 ); // variation ids of products that are gift coupons
foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
if( in_array( $values['variation_id'], $autocoupon ) ) {
$cat_in_cart = true;
}
}
if ( !$cat_in_cart ) {
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
if ( in_array( $cart_item['variation_id'], $freecoupon )) {
$woocommerce->cart->remove_cart_item($cart_item_key);
}
}
}
}
add_action( 'woocommerce_cart_item_removed', 'remove_gift_product' );
如果您想降低礼品的价格,请添加此选项。
function add_discount_price( $cart_object ) {
global $woocommerce;
$cat_in_cart = false;
$autocoupon = array( 123411 ); // variation ids of products that offers gifts
$freecoupon = array( 2046 ); // variation ids of products that are gift coupons
foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
if( in_array( $values['variation_id'], $autocoupon ) ) {
$cat_in_cart = true;
}
}
if ( $cat_in_cart ) {
$custom_price = 0; // This will be your custome price
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
if ( in_array( $cart_item['variation_id'], $freecoupon )) {
$cart_item['data']->set_price($custom_price);
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'add_discount_price' );
推荐阅读
- nlp - 构建自己的 ConceptNet 副本而不是使用他们的 REST API 会提高性能吗?
- javascript - 错误:ENOENT:没有这样的文件或目录,mkdir 在尝试创建目录时
- c - sizeof 中的字符串文字
- java - 用杰克逊读取嵌套的json - MismatchedInputException:无法反序列化值
- windows - Windows 应用程序是否通常有一个用于 StdIn、StdOut 和 StdErr 的控制台
- javascript - 使用 dayjs 和 React 在天和月中的两个日期之间存在差异
- go - 对golang切片帽感到困惑
- reactjs - TypeError:无法读取未定义的属性“参数” - ReactJS
- flutter - 如何将 Flutter 列表列表中的数据放入 ui 线程?
- typescript - 使用两次时如何缩小模板文字类型