在 WooCommerce 购物车中获取购物车商品的产品 ID

Get in WooCommerce cart the product ID of a cart item

$cart_item = $woocommerce->cart->get_cart(); 

我有上面的代码。

如果我 运行 print_r 在 cart_item 我得到一个多维数组:

Array(    [a6292668b36ef412fa3c4102d1311a62] => Array        (            [product_id] => 6803

如何才能获得 product_id?

我试过 $test = $cart_item['data'];

print_r($test);

没用。

要在 foreach 循环中获取每个购物车商品的 product ID(对于简单产品):

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'];
}

或者对于这两种情况(其中$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];
  • 获取第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