在WooCommerce购物车中获取购物车项目的产品ID [英] Get in WooCommerce cart the product ID of a cart item
问题描述
$cart_item = $woocommerce->cart->get_cart();
我有上面的代码.
如果我在cart_item上运行print_r,则会得到一个多维数组:
if I run print_r on cart_item I get a multi dimensional array:
Array( [a6292668b36ef412fa3c4102d1311a62] => Array ( [product_id] => 6803
如何仅获取product_id?
How do I get the product_id only?
我尝试了$ test = $cart_item['data'];
I tried $test = $cart_item['data'];
print_r($test);
没用.
推荐答案
要获取foreach循环中每个购物车商品的 product ID
(对于简单产品):
To get the product ID
of each cart item in the foreach loop (for a simple product):
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
}
如果是可变产品,请获取 variation ID
:
If it's a variable product, to get the variation ID
:
foreach( WC()->cart->get_cart() as $cart_item ){
$variation_id = $cart_item['variation_id'];
}
或在两种情况下(其中 $cart_item['data']
是 WC_Product
Woocommerce 3+中的对象):
Or for both cases (where $cart_item['data']
is the WC_Product
Object in Woocommerce 3+):
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
Update: Using Product ID outside the loop
1)打破循环(仅获得购物车的第一个商品ID(产品ID)):
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
break;
}
您可以直接使用购物车中第一项的$product_id
变量.
You can use directly $product_id
variable of the first item in cart.
2)使用产品ID阵列(购物车中的每个商品一个).
2) Using an array of product IDs (one for each item in cart).
$products_ids_array = array();
foreach( WC()->cart->get_cart() as $cart_item ){
$products_ids_array[] = $cart_item['product_id'];
}
- 要获取第一项产品ID:
$products_ids_array[0];
- 要获取第二项产品ID:
$products_ids_array[1];
等… - To get the 1st item product ID:
$products_ids_array[0];
- To get the 2nd item product ID:
$products_ids_array[1];
etc…
要检查购物车项目中的产品类别或产品标签,请使用WordPress has_term()
,例如:
To check product categories or product tags in cart item use WordPress has_term()
like:
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']
作为父变量商品.
We always use
$cart_item['product_id']
as we get the parent variable product when a cart item is a product variation.
产品变体不处理任何自定义分类法,即产品类别和产品标签
Product variations don't handle any custom taxonomy as product categories and product tags
这篇关于在WooCommerce购物车中获取购物车项目的产品ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!