Reputation: 1940
I have a huge list of subcategories in a category. When opening that category, I need to display only the subcategories that have images set. Is there a way to filter the category collection to display only categories that:
Upvotes: 0
Views: 922
Reputation: 16107
You can use a Magento category_collection to build a query. Magento collection queries extend Zend queries so you can use a lot of things a Zend query would allow you to use (or you can get the zend query and alter it directly).
One nice addition that Magento collection queries bring is the fact that you can filter by EAV attributes (it adds all the necessary table joins to fetch the attributes).
Another nice addition of Magento collections is the fact that it fetches information from either the current store if available or from the default store.
$categories = Mage::getResourceModel('catalog/category_collection')
->addFieldToFilter('image', array('notnull' => true))
->addFieldToFilter('parent_id', $categoryId)
->setStoreId(2);
In our case both image
and parent_id
are simply fields in the catalog_category_entity
table, they are not EAV attributes so we can use addFieldToFilter
. If they were EAV attributes we should use addAttributeToFilter
.
There is also an issue regarding how these queries work when flat tables are enabled I don't remember what the catch was exactly. For example I just tested this query using addAttributeToFilter('image'
even though the image
is a Field not an attribute, and the query worked for me because the shop I tested it in is using flat tables (in flat tables attributes are converted to fields).
There are a few performance elements to monitor:
And there are a few performance enhancements built into Magento:
Upvotes: 3
Reputation: 4073
To display the category image in place of a category name.
<?php
//gets all sub categories of parent category 'Brands'
$cats = Mage::getModel('catalog/category')->load(6)->getChildren();
$catIds = explode(',',$cats);
$categories = array();
foreach($catIds as $catId) {
$category = Mage::getModel('catalog/category')->load($catId);
$categories[$category->getName()] = array(
'url' => $category->getUrl(),
'img' => $category->getImageUrl()
);
}
ksort($categories, SORT_STRING);
?>
<ul>
<?php foreach($categories as $name => $data): ?>
<li>
<a href="<?php echo $data['url']; ?>" title="<?php echo $name; ?>">
<img class="cat-image" src="<?php echo $data['img']; ?>" />
</a>
</li>
<?php endforeach; ?>
</ul>
Upvotes: 0