Is it possible in WooCommerce to calculate the amount of products in stock minus the no of products in the cart? So
products in stock - products_in_cart
We need this so we can show 2-4 delivery days if they order more than is in stock. Normally you can use get_stock_quantity()
to get the stock quantity, but as long as the purchase is not made that does not show stock once the purchase has been made. My current code/shortcode
is this:
/**
* Register in or out of stock text shortcode
*
* @return null
*/
function imwz_register_in_or_out_stock_text_shortcode() {
add_shortcode( 'inoroutofstocktext', 'imwz_in_or_out_stock_text_check' );
}
add_action( 'init', 'imwz_register_in_or_out_stock_text_shortcode' );
function imwz_in_or_out_stock_text_check () {
global $product;
ob_start();
$output = '';
if ( ! $product->managing_stock() && ! $product->is_in_stock() ) {
echo "2-4 dagen";
}
elseif ($product->is_in_stock()) {
echo "1-2 dagen";
}
else {
echo "nothing to see here";
}
$output = ob_get_clean();
return $output;
}
This only shows what is in stock and only products sold are deducted and based on that is shows text. But I need to check if in cart causes less than in stock and then show a longer delivery date.
You could use the following to know how many pieces of a certain product are in the shopping cart
global $product;
// Get product id
$product_id = $product->get_id();
// Cart not empty
if ( WC()->cart->get_cart_contents_count() >= 1 ) {
// set variable
$in_cart = false;
// loop through the shopping cart
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product_in_cart = $cart_item['product_id'];
// Get quantity in cart
$quantity = $cart_item['quantity'];
// match
if ( $product_in_cart === $product_id ) {
$in_cart = true;
}
}
// product found
if ( $in_cart ) {
echo 'product is in het winkelwagentje, met ' . $quantity . 'stuks';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.