Magento. Sort products collection by position
Asked Answered
B

3

6

I have products collection.

$_products = Mage::getModel('catalog/product')->getCollection();

In admin panel in Catalog->Manage Categories->Category products i have position for each product. How i can sort $_products by position ?

Breather answered 3/10, 2015 at 9:46 Comment(0)
B
0

I have created separated extension which create new products attribute with name 'position'. In this extension i have create observer which listening category save event. So when admin save category in my observer i get each position and set my attribute 'position' for each product. And at at last i can sort products collection by 'position'(product) attribute.

Breather answered 4/10, 2015 at 22:14 Comment(0)
N
6

If you want to sort products by position in category $category_id. you can use the following

//Load the category model

 $category = Mage::getModel('catalog/category')->load($category_id)
             ->getProductCollection()
             ->addAttributeToSort('position', 'ASC');

$products_list = $category->getData();

you will get all products sorted by position in that category $category_id

Nomadic answered 3/10, 2015 at 10:28 Comment(2)
Hello, thank you for answer. Unfortunately ->addAttributeToSort('position', 'ASC') not working in products collectionBreather
check my edited code. In that if you know the category id, you can fetch the products in that category sorted by positionNomadic
S
2

you need to add category, where you set positions for products, as filter for collection

$category = Mage::getModel('catalog/category')->load($categoryId);
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addCategoryFilter($category);
$collection->addAttributeToSort('position', 'ASC');
Susannsusanna answered 3/10, 2015 at 13:16 Comment(0)
B
0

I have created separated extension which create new products attribute with name 'position'. In this extension i have create observer which listening category save event. So when admin save category in my observer i get each position and set my attribute 'position' for each product. And at at last i can sort products collection by 'position'(product) attribute.

Breather answered 4/10, 2015 at 22:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.