![](/img/trans.png)
[英]Get The Product Id of An Item If User Changes Quantity to 0 in WooCommerce Cart
[英]Get the cart item quantity by item id in Woocommerce
在WooCommerce中,我創建了一個迷你購物車,我希望獲取當前購物車中可用的商品數量。
正如我嘗試過的:
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$product_id = $values['product_id'];
if ( $product_id == $id ){
$product_qnty = $values['quantity'];
}
break;
}
是否有單個功能可以按購物車項目獲取購物車數量?
也許您應該首先在woocommerce模板代碼cart / mini-cart.php中查找,在那里您可以找到官方的相關代碼。
注意:“商品ID”僅在WC_Orders商品循環中可用,而在WC_Cart(“購物車鑰匙”)中不可用。 因此,您肯定在談論產品ID。 但是,如果您查看官方模板cart / mini_cart的代碼,則將需要使用WC_Product
對象而不是$product_id
……
因此,您始終可以構建一個自定義函數,例如(帶有$product
參數,WC_Product對象) ,可以在相應的模板代碼或自定義代碼中使用:
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;
}
代碼在您的活動子主題(或主題)的function.php文件中,或者在任何插件文件中。
USAGE (示例) :在這里,我們將輸出$product
的數量( WC_Product
對象) :
// Output the quantity based on the $product object
echo __('Quantity'). ': ' . get_item_qty( $product );
官方文檔: 模板結構+通過主題覆蓋模板
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.