Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento get all products in a certain category ordered by the 'Position' field

I am simply trying to get all products that belong to a certain category ID in the Position order they are set in the back end.

I seemed to have tried every example available to no avail.

The basic code I'm working with is as follows (external php file that loads magento manually):

// Load Magento
require_once $_SERVER['DOCUMENT_ROOT'] . "/app/Mage.php";
umask(0);
Mage::app();
// set Store ID
$store_id = Mage::app()->getStore()->getStoreId();
// set Cat ID
$cat_id = 345;


$cat = Mage::getModel('catalog/product')->setId(345);

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addCategoryFilter($cat)
    ->addAttributeToSelect("*")
    ->setOrder('name','asc')
    ->load();

foreach($products as $p) {
    var_dump($p->getName());
}

How might I achieve this?

like image 960
Gga Avatar asked Jan 14 '13 12:01

Gga


1 Answers

This was what finally worked:

$cat_id = 345;

$category = Mage::getModel('catalog/category')->load($cat_id);
$collection = $category->getProductCollection()->addAttributeToSort('position');
Mage::getModel('catalog/layer')->prepareProductCollection($collection);

foreach ($collection as $product) {
    var_dump( $product->getName() );
}
like image 196
Gga Avatar answered Oct 26 '22 18:10

Gga