Woocommerce how to add order Item meta to apply discount only on some items
Woocommerce how to add order Item meta to apply discount only on some items
I'd like to apply a discount on an order item from the admin panel by using the meta field on the product. There is the option to modify the input price on the right, but you can't do it with a percentage. So my idea is to apply a discount function if exists a meta field. This is my function, but it is not working:
function discount_meta($item_id, $item, $order_id){
// Get Order
$order = !empty($order) ? $order : wc_get_order($order_id);
if (!$order || !is_a($order, '\WC_Order')) {
return;
}
// Go through Order items
foreach ($order->get_items() as $item_id => $item) {
//Get product Id of the item
$product_id = (!empty($item['variation_id']) ? $item['variation_id'] : $item['product_id']);
//Get price of the item
$price = ($product = wc_get_product($product_id)) ? $product->get_price() : 0;
//Update Line Subtotal if exist discount meta
if (wc_get_order_item_meta($item_id, 'discount', true)) {
$discount = wc_get_order_item_meta($item_id, 'discount', true);
$discountval = $price * $discount / 100;
$saleprice = $price - $discountval;
wc_update_order_item_meta($item_id, '_line_total', $saleprice);
}
}
}
add_action('woocommerce_order_before_calculate_totals', 'discount_meta', 10, 3);
On the admin panel I'd like to do this:
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand