0

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.

2 Answers 2

3

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;
5
  • Thanks Nalin, but still it is not working.
    – Elavarasan
    Commented Jun 27, 2017 at 12:17
  • Updated my answer, please check Commented Jun 27, 2017 at 12:27
  • as per your new update, It will clear the old collection if it is already loaded, but unfortunately it is not working - tried, thanks.
    – Elavarasan
    Commented Jun 27, 2017 at 12:29
  • please check now Commented Jun 27, 2017 at 12:34
  • Setorder thing I already tried, sorry for not updating in my question, and I tried again it is not working, Thanks for your continues help @nalin
    – Elavarasan
    Commented Jun 27, 2017 at 12:44
0

indeed to need to specify attributes to select by

$collection->addAttributeToSelect(*);

or

$collection->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes());

And to sort you have to use this:

$collection->addAttributeToSort('you_custom_attribute_code');

Hope it will help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.