I'm trying to edit the backorder notification on the cart page in WooCommerce so that the number of backorders show for each cart item (I'm using variations).
So if a cart item has a quantity of 7 but the stock is 5, the backorder should be 2. (This information is shown on order emails by default in Woocommerce but not on the cart page before the order is made).
The code below works as long as there is only 1 cart item in the cart. But if there is more than 1 cart item, the same number of backorders is returned for all cart items with backorders.
Does anyone know what I should change so that the backorder notification will display the correct number of backorders for each individual cart item that has backorders - no matter how many cart items with backorders there are in the cart?
I'm using the filter hook woocommerce_cart_item_backorder_notification
function backorder_info() {
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// Get an instance of the WC_Product Object
$product = $cart_item['data'];
// Get stock quantity
$stock_qty = $product->get_stock_quantity();
// get cart item quantity
$item_qty = $cart_item['quantity'];
// Calculate number of backorders
$backorder_qty = $item_qty - $stock_qty;
$html = '<p class="backorder_notification">' .__( " " .$backorder_qty. " i restordre","woocommerce").'</p>';
// return backorder quantity
return $html;
}
}
// Display backorder notification on cart page
add_filter( 'woocommerce_cart_item_backorder_notification', 'custom_cart_item_backorder_notification', 10, 2 );
function custom_cart_item_backorder_notification($html, $product_id) {
$html = backorder_info();
return $html;
}