I want to show the quantity sold on the frontend for configurable products. I have this code already that works perfect for simple products. But for configurable products always shows 0.
How Can I update so it works for both, simple and configurable. Also will be cool to hide it when sold quantity is 0.
<?php
$sku = nl2br($_product->getSku());
$product = Mage::getResourceModel('reports/product_collection')
->addOrderedQty()
->addAttributeToFilter('sku', $sku)
->setOrder('ordered_qty', 'desc')
->getFirstItem();
echo 'Already Bought '.(int)$product->ordered_qty; ?>
You might be having problems because product options can change the specific SKU for an item in a quote/order. Try just looking it up product ID instead.
Something like (I haven't tried this code to test it):
Then wherever you want it to show up:
Or however you want to display it.
EDIT BELOW
I'll leave the above for consistency, but you're right, it caused the same error for me:
That annoyed me, so I dug in and didn't be lazy this time, and actually wrote some working example code. I learned something important during this, too - be sure you always have
addOrderedQty()
beforeaddIdFilter()
, or your collection will just ignore that filter entirely. Thanks, Magento.Anyway, this little self-contained example will get the Ordered Quantity and print it with the product ID, it should be pretty clear what's going on in it.
?>
Run it like this:
And you get output like this:
Hope this helps a little more than my first attempt.