2

I'm trying to get the first 4 products from a category that are in stock to show on the home page. I've got everything working the way I would like except it's pulling products that are out of stock.

I've tried addAttributeToFilter('is_in_stock', 1) and isSaleable() but those didn't work.

$collection = Mage::getModel('catalog/category')->
                    load('33')->
                    getProductCollection()->
                    addAttributeToFilter('status', 1)->
                    addAttributeToSelect('*')->
                    addAttributeToSort('position')->
                    setPageSize(4);
3

You have to pass the collection through a seperate method for that

Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);

But maybe you would be better of using the regular list.phtml including it by using the XML layout in the page CMS. that way you don't need to write any code. The snippet below should work

<block type="catalog/product_list" name="product_list" template="catalog/product/list.phtml">
   <action method="setCategoryId"><category_id>30</category_id></action>
   <action method="setLimit"><value>4</value></action>
</block>
2
  • I'm creating a custom slider that pulls in products and uses attributes to make it do certain things so the XML layout wont work for me. Your solution worked perfect for me though, thank you!
    – kel
    Apr 2 '13 at 20:54
  • Hey Kel, not to be preachy but things like "->addAttributeToSelect('*')" are not too good for performance. If you use a different template file (let's say 'catalog/product/slider.phtml) on the block you can actually build the slider on top of the normal catalog category functionality. Glad I could help, good luck with the project
    – Sander Mangel
    Apr 3 '13 at 9:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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