要获取 product ID
foreach循环中的每个购物车商品(对于简单产品):
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'];}
或在两种情况下 ( Woocommerce 3+中
$cart_item['data']的
WC_Product
Object在哪里) :
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'];}
- 要获得第一项产品ID:
$products_ids_array[0];
- 要获取第二项产品ID:
$products_ids_array[1];
etc …
要检查购物车项目中的 产品类别 或 产品标签
,请使用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']当购物车商品是产品变体时,我们总是使用它作为父变量产品。产品变体不处理任何自定义分类法,因为产品类别和产品标签
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)