Question

I am loading specific category products on a page, but it's not working properly, it's getting all the products that added.. not specificaly a category products..

Please help:

code i am using is :

$category2 = Mage::getModel('catalog/category')->load(10);
    //$products->addCategoryFilter($category);
    $products2 = Mage::getModel('catalog/product')->getCollection();
  $products2->addAttributeToSelect(array('name', 'thumbnail', 'price')); //feel free to add any other attribues you need.
  Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products2);
  Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products2); 
  $products2->getSelect()->order('RAND()');
  $products2->getSelect()->limit(3);
Was it helpful?

Solution 2

The below code is working properly:

$category = Mage::getModel('catalog/category')->load(9);
    //$products->addCategoryFilter($category);
    //$products = Mage::getModel('catalog/product')->getCollection();

    $products = Mage::getModel('catalog/product')->getCollection()->addCategoryFilter($category)->addAttributeToSelect(array('name', 'thumbnail', 'price')); 

  //$products->addAttributeToSelect(array('name', 'thumbnail', 'price')); //feel free to add any other attribues you need.
  Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
  Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products); 
  $products->getSelect()->order('RAND()');
  $products->getSelect()->limit(3);

OTHER TIPS

May be it will helpful.

<?php

    $categoryid = 12;

    $category = new Mage_Catalog_Model_Category();
    $category->load($categoryid);
    $collection = $category->getProductCollection();
    $collection->addAttributeToSelect('*');

    foreach ($collection as $_product) { ?>

    <a href="<?php echo $_product->getProductUrl() ?>"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(200); ?>" width="200" height="200" alt="" /></a> <a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $_product->getName(); ?></a>

    <?php } ?>

OR you can use this

$products = Mage::getModel('catalog/category')->load($category_id)
 ->getProductCollection()
 ->addAttributeToSelect('*') // add all attributes - optional
 ->addAttributeToFilter('status', 1) // enabled
 ->addAttributeToFilter('visibility', 4) //visibility in catalog,search
 ->setOrder('price', 'ASC'); //sets the order by price
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top