您需要在上面的代码中引入一个用于检查产品ID的语句:if
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
$custom_price = 10; // This will be your custome price
$target_product_id = 598;
foreach ( $cart_object->cart_contents as $value ) {
if ( $value['product_id'] == $target_product_id ) {
$value['data']->price = $custom_price;
}
/*
// If your target product is a variation
if ( $value['variation_id'] == $target_product_id ) {
$value['data']->price = $custom_price;
}
*/
}
}
将此代码添加到任何位置,并确保此代码始终是可执行的。
添加此代码后,当您调用:
global $woocommerce;
$woocommerce->cart->add_to_cart(598);
只有此产品将以覆盖的价格添加,添加到购物车的其他产品将被忽略以覆盖价格。
希望这会有所帮助。