Programmatically change an item price when adding it to an order
-
Hello,
I have a script that runs when the admin intends to add an item to an order in the admin. The function looks for the previous orders of the customer in order to find the customer’s price for the product (the prices in the shop depends of the roles the customer has).
The function works and finds the correct price, but I only manage to set it as the total of the line, instead as the price of the price.In this example the correct price of the product, for this customer, is 13,20€. Here is what I get : https://snipboard.io/nGgvOV.jpg The price discounted is considered as a coupon when it should not
What I want is : https://snipboard.io/rXO1iH.jpg
Is there a way to programmatically set those price, as if I was doing this : https://snipboard.io/1SZlUs.jpgThanks in advance…
EtienneMy current code :
function action_woocommerce_new_order_item( $item_id, $item, $order_id ) { // only run this from the WP admin section using Ajax if( !is_admin() || !defined('DOING_AJAX') || !DOING_AJAX ) : return; endif; // return if this is not a product (i.e. fee, tax, etc.) $item_type = $item->get_type(); if( $item_type != 'line_item' ) : return; endif; $product_id = $item->get_product_id() ; $product = wc_get_product( $product_id ) ; if( !$product ) : return; endif; $current_price = $product->get_price(); $order = wc_get_order( $order_id ); $order_user = $order->get_user(); $order_user_id = $order->get_user_id(); // on récupère toutes les commandes de cet utilisateur, de la plus ancienne à la plus récente $user_orders = get_posts(apply_filters('woocommerce_my_account_my_orders_query', array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => $order_user_id, 'post_type' => 'shop_order', 'post_status' => 'wc-completed', 'order' => 'ASC', 'exclude' => array($order_id), ))); //print_r($user_orders); // pour chacune de ces commandes, on regarde si c'est une commande dép?t vente, puis on regarde si le produit qu'on cherche y est, s'il y est on stocke son prix (écrasant éventuellement un précédent) foreach($user_orders as $user_order) : if(get_field('type_commande',$user_order->ID) != 'sous-depot-vente') : $user_order = wc_get_order( $user_order->ID ); $user_order_items = $user_order->get_items() ; foreach($user_order_items as $user_order_item) : $item_product_id = $user_order_item->get_product_id() ; if($item_product_id == $product_id) : $total = $user_order_item->get_total() ; $quantity = $user_order_item->get_quantity() ; $prix_anterieur = floatval($total)/$quantity ; endif; endforeach ; endif; endforeach; $quantity = $item->get_quantity(); if(isset($prix_anterieur)) : $new_price = $prix_anterieur ; else : $new_price = $current_price ; endif ; $item->set_total( $new_price * $quantity ); }; add_action( 'woocommerce_new_order_item', 'action_woocommerce_new_order_item', 10, 3 );
- The topic ‘Programmatically change an item price when adding it to an order’ is closed to new replies.