Dynamically changing basket position does not work with orders in WooCommerce 3.0+

I use WooCommerce 3.0+ and I set the price of the product on a specific page.

$regular_price = get_post_meta( $_product->id, '_regular_price', true); $buyback_percentage = get_post_meta( $_product->id, '_goldpricelive_buy_back', true); $fixed_amount = get_post_meta( $_product->id, '_goldpricelive_fixed_amount', true); $markedup_price = get_post_meta( $_product->id, '_goldpricelive_markup', true); $buyback_price = ($regular_price - $fixed_amount)/(1 + $markedup_price/100) * (1-$buyback_percentage/100); $_product->set_price($buyback_price); 

The price is updated on my cart, but when I click to send my order, the order object does not seem to receive the price that I set. He takes the initial price of the product.

Any idea on how I can do this?

thanks

+2
php wordpress woocommerce cart
source share
1 answer

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 ...

+2
source share

All Articles