Get Simple Product from Configurable in Cart
Asked Answered
F

1

11

I'm trying to load the simple products that have been added to a customer's cart, but when I retrieve the items, it's showing the parent configurable.

$cart = Mage::getSingleton('checkout/cart');
$productIds = array();

foreach ($cart->getQuote()->getAllVisibleItems() as $item) {
    $productIds[] = $item->getProduct()->getId();
}

var_dump($productIds);

For instance, this will return all the same configurable id when I've added a small, medium, and large to my cart. How can I get the individual simple products? I'm trying to retrieve an attribute value that's set on the simple product level.

Frechette answered 2/8, 2013 at 23:16 Comment(0)
F
24

After taking a look at how Magento renders the items in your cart on the checkout/cart page, I was able to find this in app/code/core/Mage/Checkout/Block/Cart/Item/Renderer/Configurable.php

/**
 * Get item configurable child product
 *
 * @return Mage_Catalog_Model_Product
 */
public function getChildProduct()
{
    if ($option = $this->getItem()->getOptionByCode('simple_product')) {
        return $option->getProduct();
    }
    return $this->getProduct();
}

So, applying it to the snippet in the question, it would be

foreach ($cart->getQuote()->getAllVisibleItems() as $item) {
    $productId = $item->getProduct()->getId();
    if ($option = $item->getOptionByCode('simple_product')) {
        $productId = $option->getProduct()->getId();
    }
    $productIds[] = $productId;
}
Frechette answered 2/8, 2013 at 23:43 Comment(1)
For others : A one line code : $_item->getOptionByCode('simple_product')->getProduct()->getId();Gott

© 2022 - 2024 — McMap. All rights reserved.