I am trying to create a function for wordpress/woocommerce to show an option in the cart page for split delivery.
What it should do is to check the stock status of all items in cart.
First case: If all items in cart are available output nothing.
Second case: If all items in cart are out of stock, output nothing.
Third case: The only condition when something should be shown is, when both cases (first and second) occurs.
So only if the cart has items in stock AND has items out of stock it should display a notification.
The previous version seemed to be the wrong way to go. So here is my new approach with a different code.
in functions.php:
add_action( 'woocommerce_after_cart_table', 'split_devliery_notification' );
function split_devliery_notification() {
$all_items_in_stock = true; // initializing
$all_items_out_of_stock = true;
// Iterating through cart items (to get the stock info)
foreach (WC()->cart->get_cart() as $cart_item) {
# HANDLING SIMPLE AND VARIABLE PRODUCTS
// Variable products
$variation_id = $cart_item['variation_id'];
if( 0 != $variation_id) {
$variation_obj = new WC_Product_variation($variation_id);
$stock = $variation_obj->get_stock_quantity();
} else {
// Simple products
$product_id = $cart_item['product_id'];
$product_obj = new WC_Product($product_id);
$stock = $product_obj->get_stock_quantity();
}
if( $stock <= 0 ){
// if an item is out of stock
$all_items_in_stock = false;
break; // We break the loop
}
elseif ( $stock >= 0 ) {
$all_items_out_of_stock = false;
break;
}
}
// All items "in stock"
if( $all_items_in_stock ) {
echo 'All items in cart are in stock';
}
elseif ( $all_items_out_of_stock ) {
echo 'All items in cart are out of stock';
}
else {
echo 'Some items in cart are in stock and some are out of stock -> Show notification ON!';
}
}
This function works for two cases:
- If all items in cart are in stock it echoes the right message (All items in cart are in stock ).
- If all items in cart are out of stock is echoes the right message (All items in cart are out of stock).
But if the cart contains items in stock AND items out of stock it echoes the first message (All items in cart are in stock).