Updated with get_price()
method …
You should use woocommerce_before_calculate_totals
action hook setting inside this custom hooked function, your products IDs or an array of product IDs.
Then for each of them you can make a custom calculation to set a custom price that will be set on Cart, checkout and after submitting in the order.
Here is that functional code tested on WooCommerce version 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;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
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) );
}
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
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…
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…