$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循环中每个购物车项目的产品ID(对于简单产品):
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
}
如果它是变量产品,要获取变体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
}
}
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变量.
2)使用产品ID数组(购物车中的每个项目一个).
$products_ids_array = array();
foreach( WC()->cart->get_cart() as $cart_item ){
$products_ids_array[] = $cart_item['product_id'];
}
>获取第一项产品ID:$products_ids_array [0];
>获取第2项产品ID:$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
}
}
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