当购物车中的数量达到阈值时,我正在尝试更改产品变化的价格。
我的工作来自:WooCommerce: Get custom field from product variations and display it on the “additional information area”和WooCommerce: Bulk Dynamic Pricing Without a Plugin
这是我所拥有的:
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 quatity has reached the defined threasold
if( $cart_item['quantity'] >= $threshold && $bulk_price > 0 ) {
// Set the bulk price
$cart_item['data']->set_price( $bulk_price );
}
}
}
代码进入您的活动子主题(或活动主题)的functions.php文件中。应该可以。