您应该需要将 $cart_item['product_id'] 替换为 $cart_item['variation_id'] 以使其适用于您条件下的产品变化。
这个函数只会改变显示,不会改变计算:
// Changing the displayed price (with custom label)
add_filter( 'woocommerce_cart_item_price', 'sv_display_product_price_cart', 10, 3 );
function sv_display_product_price_cart( $price, $cart_item, $cart_item_key ) {
if ( 142 == $cart_item['variation_id'] ) {
// Displaying price with label
$price = '$50.00 per Unit<br>(7-8 skewers per Unit)';
}
return $price;
}
这是一个钩子函数,它将根据您的价格更改购物车计算:
// Changing the price (for cart calculation)
add_action( 'woocommerce_before_calculate_totals', 'sv_change_product_price_cart', 10, 1 );
function sv_change_product_price_cart( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach ( $cart->get_cart() as $cart_item ) {
if ( 142 == $cart_item['variation_id'] ){
// Set your price
$price = 50;
// WooCommerce versions compatibility
if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
$cart_item['data']->price = $price; // Before WC 3.0
} else {
$cart_item['data']->set_price( $price ); // WC 3.0+
}
}
}
}
代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。
所以你会得到:
此代码在 Woocommerce 版本 2.6.x 和 3.0+ 上经过测试广告作品