Updated using get_price() method ...
You must use the woocommerce_before_calculate_totals action parameter in this custom function, product identifiers or an array of product identifiers.
Then, for each of them, you can make your own calculation to set a custom price, which will be set in the basket, statement and after sending in the order.
Here is the 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; // 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) ); } } }
The code goes in the function.php file of your active child theme (or theme), as well as in any plugin file.
Then you can easily replace the fixed values ββin my fake calculations with the dynamic values ββof your product using the get_post_meta () function, as in your code, since you have $product_id for each basket item ...
LoicTheAztec
source share