![](/img/trans.png)
[英]Get The Product Id of An Item If User Changes Quantity to 0 in WooCommerce Cart
[英]Get in WooCommerce cart the product ID of a cart item
$cart_item = $woocommerce->cart->get_cart();
我有上面的代碼。
如果我在cart_item 上運行print_r,我會得到一個多維數組:
Array( [a6292668b36ef412fa3c4102d1311a62] => Array ( [product_id] => 6803
如何僅獲取 product_id?
我試過 $test = $cart_item['data'];
print_r($test);
沒用。
要獲取 foreach 循環中每個購物車項目的product ID
(對於簡單產品):
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
}
如果是可變產品,要獲取variation ID
:
foreach( WC()->cart->get_cart() as $cart_item ){
$variation_id = $cart_item['variation_id'];
}
或者對於這兩種情況(其中$cart_item['data']
是Woocommerce 3+ 中的WC_Product
對象) :
foreach( WC()->cart->get_cart() as $cart_item ){
// compatibility with WC +3
if( version_compare( WC_VERSION, '3.0', '<' ) ){
$product_id = $cart_item['data']->id; // Before version 3.0
} else {
$product_id = $cart_item['data']->get_id(); // For version 3 or more
}
}
更新:在循環外使用產品 ID
1)打破循環(只是為了獲得購物車的第一個項目ID(產品ID)) :
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
break;
}
您可以直接使用購物車中第一件商品的$product_id
變量。
2) 使用一組產品 ID (購物車中的每件商品一個) 。
$products_ids_array = array();
foreach( WC()->cart->get_cart() as $cart_item ){
$products_ids_array[] = $cart_item['product_id'];
}
$products_ids_array[0];
$products_ids_array[1];
等等… 要檢查購物車項目中的產品類別或產品標簽,請使用 WordPress has_term()
例如:
foreach( WC()->cart->get_cart() as $cart_item ){
// For product categories (term IDs, term slugs or term names)
if( has_term( array('clothing','music'), 'product_cat', $cart_item['product_id'] ) ) {
// DO SOMETHING
}
// For product Tags (term IDs, term slugs or term names)
if( has_term( array('clothing','music'), 'product_tag', $cart_item['product_id'] ) ) {
// DO SOMETHING ELSE
}
}
當購物車項目是產品變體時,我們總是使用
$cart_item['product_id']
來獲取父變量 product。產品變體不處理任何自定義分類作為產品類別和產品標簽
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.