Solution:
The cart_contents
variable of the cart object (WC()->cart->cart_contents
) includes an array of information for each item in the cart… a var_dump
of my sample cart contents looks like the following:
["cart_contents"]=> array(1) {
["7cbbc409ec990f19c78c75bd1e06f215"]=>
array(5) {
["product_id"]=> int(70)
["variation_id"]=> string(0) ""
["variation"]=> string(0) ""
["quantity"]=> int(1)
["data"]=> object(WC_Product_Simple)#530 (3) {
["id"]=> int(70)
["post"]=> object(WP_Post)#532 (24) {
["ID"]=> int(70)
["post_author"]=> string(1) "1"
["post_date"]=> string(19) "2013-06-07 11:25:01"
["post_date_gmt"]=> string(19) "2013-06-07 11:25:01"
["post_content"]=> string(278) "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo."
["post_title"]=> string(12) "Flying Ninja"
["post_excerpt"]=> string(278) "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo."
["post_status"]=> string(7) "publish"
["comment_status"]=> string(4) "open"
["ping_status"]=> string(6) "closed"
["post_password"]=> string(0) ""
["post_name"]=> string(12) "flying-ninja"
["to_ping"]=> string(0) ""
["pinged"]=> string(0) ""
["post_modified"]=> string(19) "2014-10-06 16:53:48"
["post_modified_gmt"]=> string(19) "2014-10-06 16:53:48"
["post_content_filtered"]=> string(0) ""
["post_parent"]=> int(0)
["guid"]=> string(67) "http://demo2.woothemes.com/woocommerce/?post_type=product&p=70"
["menu_order"]=> int(0)
["post_type"]=> string(7) "product"
["post_mime_type"]=> string(0) ""
["comment_count"]=> string(1) "4"
["filter"]=> string(3) "raw"
}
["product_type"]=> string(6) "simple"
}
}
}
Therefore, in a foreach()
loop over the cart contents, the product ID would be grabbed like so:
$contents = WC()->cart->cart_contents;
if( $contents ) foreach ( $contents as $cart_item ){
echo $cart_item['product_id'];
}
If you already have the specific $cart_item
variable (ex: you are in the cart template and already inside Woo’s loop) then you’d just access the product_id
array. $cart_item['product_id'];
I always find it helpful to use var_dump()
or print_r()
to know what variables or array keys are available to me.
As an aside, you might want to take a look at Product Add-ons which would do exactly what you are describing.