$cart_item = $woocommerce->cart->get_cart();
我有上面的代码。
如果我在cart_item上运行print_r,我将得到一个多维数组:
Array( [a6292668b36ef412fa3c4102d1311a62] => Array ( [product_id] => 6803
我如何只获得product_id?
我试过$ test = $cart_item['data'];
$cart_item['data'];
print_r($test);
没用
要获取 product ID foreach循环中的每个购物车商品(对于简单产品):
product ID
foreach( WC()->cart->get_cart() as $cart_item ){ $product_id = $cart_item['product_id']; }
如果是可变产品,请获取 variation ID :
variation ID
foreach( WC()->cart->get_cart() as $cart_item ){ $variation_id = $cart_item['variation_id']; }
或在两种情况下 ( Woocommerce 3+中$cart_item['data'] 的 WC_Product Object在哪里) :
$cart_item['data']
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购物车中第一项的变量。
$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()例如:
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']当购物车商品是产品变体时,我们总是使用它作为父变量产品。 产品变体不处理任何自定义分类法,因为产品类别和产品标签
$cart_item['product_id']当购物车商品是产品变体时,我们总是使用它作为父变量产品。
$cart_item['product_id']
产品变体不处理任何自定义分类法,因为产品类别和产品标签