$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']
是 WC_Product
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
}
}
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];
- 要获取第二个项目的产品 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
关于php - 在 WooCommerce 购物车中获取购物车商品的产品 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41104409/