I'm trying to get a list of categories (ID, Name). However, only categories that contain products with a certain product attribute value can be listed.
I've already tried the following;
<?php
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToFilter('product_supplier', '5');
foreach($categories as $category) {
echo $category->getName().'<br>';
}
And;
<?php
$category = Mage::getModel('catalog/category');
$catTree = $category->getTreeModel()->load();
$catIds = $catTree->getCollection()
->addAttributeToFilter('product_supplier', '5')
->getAllIds();
$cats = array();
if ($catIds){
foreach ($catIds as $id){
$cat = Mage::getModel('catalog/category');
$cat->load($id);
$cats[$cat->getId()] = $cat->getName();
}
}
But, I keep getting the error: Call to a member function getBackend() on a non-object
I found out that this error occurs when the collection tries to filter on the category, so i guess it thinks i i meant to filter by the category attribute product_supplier. I really don't know what to try next.
Suggestions?
=> My solution so far:
$catIds = array();
$validCategories = array();
//get the filtered product collection
$productCollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('product_supplier', '5');
// Loop through products, throw category id's into array
foreach($productCollection as $product) {
$catIds = array_merge($catIds,$product->getCategoryIds());
}
/**
* Loop through category id's, load categories and get name,
* create the final array
*/
foreach ($catIds as $x => $catId) {
$cat = Mage::getModel('catalog/category')->load($catId);
$validCategories[$cat->getId()] = $cat->getName();
}
getBackend()
calls