Skip to content

Instantly share code, notes, and snippets.

@AndresInSpace
Last active October 4, 2018 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndresInSpace/7c1aa699c18dab5b476f7fa0da6e4e22 to your computer and use it in GitHub Desktop.
Save AndresInSpace/7c1aa699c18dab5b476f7fa0da6e4e22 to your computer and use it in GitHub Desktop.
Get Magento Product Collection filtered by category and ordered by product position from that category without loading category model and subsequent overhead
<?php
public function getProductCollection(){
if($_category = Mage::registry('current_category')){
$_categoryId = $_category->getId();
$_productCollection = Mage::getResourceModel('catalog/product_collection');
$_productCollection->joinTable(array('cp'=>'catalog/category_product'), 'product_id=entity_id', array('*') ,'cp.category_id='.$_categoryId, 'inner'); //join the table we need, filtered on Category ID
$_productCollection
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes()) //attributes needed from products using default config, or select your own
->addAttributeToFilter('status', 1) //ensure its enabled
->addAttributeToFilter('visibility', array('in'=>array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG,Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH))) //ensure its viewable on catalog
->addMinimalPrice() //min price
->addFinalPrice() //final prices
->addTaxPercents() //taxes
->addUrlRewrite($_categoryId); //build the urls for getProductUrl()
$_productCollection->getSelect()->order('cp.position ASC'); //order by positioning defined in category
return $_productCollection;
}
}
/**** BENCHMARKS
0.0428 1 327,016 0
compared to
0.1342 1 2,611,768 2,883,584
which is using
$category=Mage::getModel('catalog/category)->load($id);
$category->getProductCollection()
etc
***/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment