1

I'm trying to sort a product collection by custom product attribute on a category landing page - the attribute is a number that corresponds to a number on an exploded view image.

at the top of the product listing block we have this:

$_productCollection = $this->getLoadedProductCollection();

which would seem to indicate that the product collection for the current category has already been loaded by something else. but I don't see that happening in either the template or parent block.

How can I replace the $_productCollection with a collection of products from the current category sorted by my custom product attribute "getexploded_view_ref"

1 Answer 1

1

One thing you can do most of the times in Magento (and which probably would also work in this case) is to start from zero. By that I mean you don't have to rely on previously loaded data but can start getting the data you want by starting at the corresponding Mage model which you can call with Mage::getModel('model/youwant') in nearly every place of Magento (so also phtml template files for example).

So to get the collection of products of a certain category and sort them by an attribute in general you would have to do something like this:

$categoryCollection  = Mage::getModel('catalog/category')
    ->load($yourCategoryId)
    ->getProductCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToSort('getexploded_view_ref', 'asc');

Now you would have the full collection of products in the category with the ID $yourCategoryId sorted ascendingly by getexploded_view_ref and can use it further depending on where and how you want to use it. Obviously you also could add other attribute filters, limit results and so on (see this link for example for an overview what you can do with collections). Note that the example above contains all products, incl. deactivated and invisible products, so you most likely will want to add attribute filters for these attributes at least. Depending on where you are there may be helper functions for such and other tasks (like for example the prepareProductCollection() of Mage_Catalog_Model_Layer which you should use when you use layered navigation).

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.