Magento – Sorting custom attribute not working in magento

magento-1.9product-collectionsorting

I need to sort the product collection by custom attribute called popular which having value 1 or 0. Below is my code,

    $collection1 = Mage::getModel('catalog/product')->getCollection();
    $collection1->addAttributeToFilter(array(array('attribute' => 'status', 'eq' => 1)));
    $collection1->addAttributeToSelect(array(array('attribute'=> 'price')));
    $collection1->addAttributeToSelect(array(array('attribute'=> 'special_price')));
    $collection1->addAttributeToSort('popular', 'desc');
    foreach ($collection1 as $col) {
                        echo $col->getId();
                        echo '<br>';

    }
    exit;

Here I just printing the product id and every load it is showing different products. I re-indexed the products and I have set the product attribute options all to yes in admin. Like Used for Sorting in Product Listing to yes, Used in Product Listing to yes, but still Im not getting unique product list. Is there something I missed here ..? And if we apply two sorting to the collections which sort will it take ?. please help me.

Note: I have tried with price attribute type for this attribute but still no luck (I thought if the attribute type is price then sorting will work correctly)

Update 1: I already tried with setorder, but that is also not working.

Best Answer

Please add attribute to select then apply sorting by using order()

    $collection1 = Mage::getModel('catalog/product')->getCollection();
    $collection1->addAttributeToSelect('*');
    $collection1->addAttributeToFilter(array(array('attribute' => 'status', 'eq' => 1)));
    //$collection1->addAttributeToSort('popular', 'desc');
$collection1->getSelect()->order('popular DESC');
    foreach ($collection1 as $col) {
                        echo $col->getId();
                        echo '<br>';

    }
    exit;
Related Topic