gpt4 book ai didi

php - 根据自定义字段和数量阈值更改 WooCommerce 购物车商品价格

转载 作者:行者123 更新时间:2023-12-04 09:53:42 27 4
gpt4 key购买 nike

当购物车商品数量达到特定阈值时,我正在尝试通过定义为产品自定义字段(产品自定义元数据)的批量价格更改来自产品变体的购物车商品价格.

我的工作地点: 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 Hook ...尝试改为:

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 文件。它应该有效。

关于php - 根据自定义字段和数量阈值更改 WooCommerce 购物车商品价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61972080/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com