I'm trying to get the names of the ordered products through my functions.php file with a loop. Heres's my code:
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = $values['data']->post;
}
And then i call the title like this:
$_product->post_title
This works, it returns me the name of the product I ordered. The thing is when i have 2 or more products it still returns me 1 name. How can i make it so it returns all the names in the cart.
The new syntax in woocommerce relative to cart is made with WC()
without any need of calling global woocommerce;
So your code will be this:
$products_in_cart= array();
$products_post_title_in_cart = array();
$products_ids_in_cart= array();
foreach(WC()->cart->get_cart() as $cart_item) {
$products_in_cart[] = $cart_item['data']->post;
$products_post_title_in_cart[] = $cart_item['data']->post->post_title;
$products_ids_in_cart[] = $cart_item['product_id'];
}
// The first product (or item of the cart)
$_product = $products_in_cart[0]; // product post data
$product_id = $products_ids_in_cart[0]; // product ID
$products_post_title_in_cart[0] // product post title
// The Second product (or item of the cart)
$_product = $products_in_cart[1]; // product post data
$product_id = $products_ids_in_cart[1]; // product ID
$products_post_title_in_cart[1] // product post title
// etc … for all other products you increase the key of the arrays to get the correct values