在WooCommerce中是否可以计算库存产品数量减去购物车中的产品数量?所以
products in stock - products_in_cart
我们需要这个,所以如果他们订购的数量超出库存,我们可以显示2-4个交货日。通常,您可以使用get_stock_quantity()
来获取库存数量,但是只要不进行购买就不会显示库存。我当前的code/shortcode
是这样的:
/**
* 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;
}
这仅显示库存中的商品,并且仅扣除出售的产品,并以此为基础显示文字。但是我需要检查购物车中的原因是否少于库存,然后显示更长的交货日期。
答案 0 :(得分:1)
您可以使用以下信息来了解购物车中有多少种特定产品
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';
}
}