简体   繁体   English

产品库存数量 - 购物车中的产品数量

[英]Product Stock Quantity - No of Products in Cart

Is it possible in WooCommerce to calculate the amount of products in stock minus the no of products in the cart?在 WooCommerce 中是否可以计算库存产品的数量减去购物车中的产品数量? 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.我们需要这个,所以如果他们订购的数量超过库存,我们可以显示 2-4 个交货天数。 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.通常您可以使用get_stock_quantity()来获取库存数量,但只要没有进行购买,一旦购买就不会显示库存。 My current code/shortcode is this:我当前的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;
}

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';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM