php - 根据自定义字段和数量阈值更改 WooCommerce 购物车商品价格
问题描述
当购物车项目数量达到特定阈值时,我正在尝试通过定义为产品自定义字段(产品自定义元数据)的批量价格从产品变体中更改购物车项目价格。
我的工作来自: WooCommerce:从产品变体中获取自定义字段并将其显示在“附加信息区域”</a> 和WooCommerce:无需插件的批量动态定价
这就是我所拥有的:
add_action( 'woocommerce_before_calculate_totals', 'bbloomer_quantity_based_pricing', 9999 );
function bbloomer_quantity_based_pricing( $cart, $variation_data ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
//get
$bulk_price = get_post_meta( $variation_data[ 'variation_id' ], 'bulk_price', true);
if ( $bulk_price ) {
$threshold1 = 6; // Change price if items > 6
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['quantity'] >= $threshold1 ) {
$price = $bulk_price;
$cart_item['data']->set_price( $price );
}
}
}
}
但它不起作用,因为我无法获得批量价格的自定义字段值。
解决方案
在您的代码$variation_data['variation_id']
中未将钩子定义为 $variation_data
不存在woocommerce_before_calculate_totals
...请尝试以下操作:
add_action( 'woocommerce_before_calculate_totals', 'quantity_based_bulk_pricing', 9999, 1 );
function quantity_based_bulk_pricing( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Define the quantity threshold
$qty_threshold = 6;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Get the bulk price from product (variation) custom field
$bulk_price = (float) $cart_item['data']->get_meta('bulk_price');
// Check if item quantity has reached the defined threshold
if( $cart_item['quantity'] >= $qty_threshold && $bulk_price > 0 ) {
// Set the bulk price
$cart_item['data']->set_price( $bulk_price );
}
}
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。它应该有效。
推荐阅读
- jboss - Teiid 与 Jboss 数据虚拟化中的 OData $search 支持
- python - 如何获得在 Windows 10 中运行 Python 代码的权限
- python - Pandas 处理大型 CSV 数据
- ios - 不支持将桥接头与模块接口一起使用 Command CompileSwiftSources failed with a nonzero exit code
- linux - 在 Linux 中找出两个目录之间丢失的文件(缺少文件名,但不是扩展名)
- ibm-cloud - 自然语言分类器教程 - 发生 500 错误
- python - 尝试利用库进行一些主题建模,但进展不顺利
- c# - 将数组一分为二,以找到获得相等或几乎相等的整数和的最佳解决方案
- python - 值在数据库上时注册帐户(窗口)拒绝(MySQL)
- java - 如何在android中使用圆角矩形自定义图像视图