首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >产品库存数量-购物车中的产品数量

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

Stack Overflow用户
提问于 2020-03-04 14:29:45
回答 1查看 220关注 0票数 0

是否可以在WooCommerce中计算库存中的产品数量减去购物车中的产品数量?所以

代码语言:javascript
运行
复制
products in stock - products_in_cart

我们需要这个,以便我们可以显示2-4个交货天数,如果他们的订单超过库存。通常,您可以使用get_stock_quantity()来获取库存数量,但是只要没有进行购买,那么一旦进行了购买,就不会显示库存。我当前的code/shortcode是:

代码语言:javascript
运行
复制
/**
 * 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;
}

这只显示了库存,只有售出的产品才会被扣除,并在此基础上显示文本。但我需要检查是否在购物车导致低于库存,然后显示较长的交货日期。

EN

回答 1

Stack Overflow用户

发布于 2020-03-04 16:20:19

您可以使用以下内容来了解购物车中有多少件特定产品

代码语言:javascript
运行
复制
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';
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60520230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档