使用get_price()方法更新…
您应该在此自定义附加功能,产品ID或产品ID数组中使用woocommerce_before_calculate_totals操作挂钩设置.然后,对于每个人,您可以进行自定义计算,以设置将在购物车,结帐时和订单提交后设置的自定义价格.
这是在WooCommerce 3.0版上测试的功能代码:
add_action( 'woocommerce_before_calculate_totals', 'adding_custom_price', 10, 1);
function adding_custom_price( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set below your targeted individual products IDs or arrays of product IDs
$target_product_id = 53;
$target_product_ids_arr = array(22, 56, 81);
foreach ( $cart_obj->get_cart() as $cart_item ) {
// The corresponding product ID
$product_id = $cart_item['product_id'];
// For a single product ID
if($product_id == $target_product_id){
// Custom calculation
$price = $cart_item['data']->get_price() + 50;
$cart_item['data']->set_price( floatval($price) );
}
// For an array of product IDs
elseif( in_array( $product_id, $target_product_ids_arr ) ){
// Custom calculation
$price = $cart_item['data']->get_price() + 30;
$cart_item['data']->set_price( floatval($price) );
}
}
}
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.
Then you can easily replace the fixed values in my fake calculations by your product dynamic values with that with get_post_meta() function just like in your code as you have the $product_id for each cart item…