I am using WooCommerce 3.0+ and I have set the product price on a certain page.
$regular_price = get_post_meta( $_product->id, \'_regular_price\',
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…