![](/img/trans.png)
[英]WooCommerce $product->get_stock_quantity(); breaking cart page
[英]Product Stock Quantity - No of Products in Cart
在 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;
}
這僅顯示庫存中的商品,並且僅扣除已售出的產品,並以此為基礎顯示文本。 但我需要檢查購物車中是否導致庫存不足,然后顯示更長的交貨日期。
您可以使用以下內容來了解購物車中某個產品的數量
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';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.