Show Quantity Sold On Product Page for Configurable - Magento

926 views Asked by At

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; ?>
1

There are 1 answers

2
Mike On

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):

<?php
     $product = Mage::getResourceModel('reports/product_collection')
         ->addOrderedQty()
         ->addAttributeToFilter('id',$_product->getID())
         ->setOrder('ordered_qty', 'desc')
         ->getFirstItem();
     $sold = (int)$product->ordered_qty;
?>

Then wherever you want it to show up:

<?php
    if ($sold > 0) {
         echo "Already sold $sold times.";
    }
?>

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:

Fatal error: Call to a member function getBackend() on a non-object in ~app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 816

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() before addIdFilter(), 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.

<?php
require_once '<path_to_magento_root>/app/Mage.php';
Mage::app('default');

$p = Mage::getResourceModel('reports/product_collection')
  ->addOrderedQty()
  ->addIdFilter($argv[1])
  ->getFirstItem();

echo $p->getId().": ".$p->ordered_qty.PHP_EOL;

?>

Run it like this:

php test.php 131

And you get output like this:

131: 103.0000

Hope this helps a little more than my first attempt.