$cart_item = $woocommerce->cart->get_cart();
Ich habe den obigen Code.
wenn ich print_r auf cart_item ausführe, erhalte ich ein mehrdimensionales Array:
Array( [a6292668b36ef412fa3c4102d1311a62] => Array ( [product_id] => 6803
Wie erhalte ich nur die product_id?
Ich habe versucht, $ test = $cart_item['data'];
print_r($test);
Hat nicht funktioniert.
So erhalten Sie den product ID
jedes Warenkorbelements in der foreach-Schleife (für ein einfaches Produkt):
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
}
Wenn es sich um ein variables Produkt handelt, erhalten Sie den variation ID
:
foreach( WC()->cart->get_cart() as $cart_item ){
$variation_id = $cart_item['variation_id'];
}
Oder für beide Fälle (wo$cart_item['data']
ist dasWC_Product
Objekt in 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: Verwenden der Produkt-ID außerhalb der Schleife
1) Breaking the Loop (Nur um die erste Artikel-ID (Produkt-ID) des Einkaufswagens zu erhalten:
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
break;
}
Sie können die Variable $product_id
Des ersten Artikels im Warenkorb direkt verwenden.
2) Verwenden einer Reihe von Produkt-IDs (eine für jeden Artikel im Warenkorb).
$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];
etc…Um Produktkategorien oder Produkt-Tags im Warenkorb zu überprüfen, verwenden Sie WordPress has_term()
wie:
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
}
}
Wir verwenden immer
$cart_item['product_id']
, Da wir das übergeordnete variable Produkt erhalten, wenn ein Warenkorbartikel eine Produktvariante ist.Produktvarianten behandeln keine benutzerdefinierten Taxonomien als Produktkategorien und Produkt-Tags