dongxueji2838 2017-10-28 03:43
浏览 213
已采纳

在Woocommerce中按项目ID获取购物车项目数量

In WooCommerce, I have created a mini cart and I want the get the item quantity available in the current cart.

As i have tried this:

  $items = $woocommerce->cart->get_cart();

      foreach($items as $item => $values) {
          $product_id = $values['product_id'];
          if ( $product_id == $id ){
            $product_qnty = $values['quantity'];
          }
          break;
      }

Is there any single function to get the cart item quantity by cart item ?

  • 写回答

1条回答 默认 最新

  • dongqie5529 2017-10-28 13:05
    关注

    May be you should look first in the woocommerce template code cart/mini-cart.php where you will find the official related code.

    Note: The "item ID" is only available in WC_Orders items loop, but not in WC_Cart which is a "Cart item Key". So you are surely talking about the product ID. But if you look to the code of the official template cart/mini_cart you will need to use the WC_Product object instead of the $product_id

    So you can always build a custom function like (with a $product argument, the WC_Product object) that you can use in the corresponding template code or in your custom code:

    function get_item_qty( $product ){
        foreach( WC()->cart->get_cart() as $cart_item )
            // for variable products (product varations)
            $product_id = $product->get_parent_id();
            if( $product_id == 0 || empty( $product_id ) )
                $product_id = $product->get_id();
    
            if ( $product_id == $cart_item['product_id'] ){
                return $cart_item['quantity'];
                // break;
            }
        return;
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


    USAGE (example): Here we will output the quantity of the $product (WC_Product object):

    // Output the quantity based on the $product object
    echo __('Quantity'). ': ' . get_item_qty( $product );
    

    Official Documentation: Template Structure + Overriding Templates via a Theme

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据