Magento 1.6 – Fixing Anchor Showing Products from Disabled Subcategories

categorycollection;magento-1.6

I have a categorie with is anchor = true.

In this categorie I display all the products of all the subcategories. For that I have a special CMS Block where I include another template:

{{block type="catalog/navigation" name="catalog.categories" template="catalog/navigation/myview.phtml"}}

I think that is not so relevant. More relevant is, in this template I get myself a product collection:

$magentoCurrentCategory = Mage::registry('current_category');
$collection = $magentoCurrentCategory->getProductCollection()->distinct(true)->addAttributeToSelect('*');
foreach ($collection as $_product) { 
// do something
}

The problem now is, with this I get all products, even products from subcategories that are disabled.

How can I get all products of subcategories, but only from subcategories that are enabled?

Best Answer

I covered this very topic in a blog of mine: http://www.proxiblue.com.au/blog/Collection_of_products_in_all_child_categories/

Since we don't want a link-fest, I include the relevant parts (but the link back does not hurt ;) )

Basically, you are not going to get this right, using the built in getProductCollection() method, but need to build the collection directly. (if someone knows why/how, please do chirp in)

So what I did , was first to get a list of categories I am interested in (this will give you the ability to filter out disabled categories)

if ($category->hasChildren()) {
                $categoryLimit = explode(',',$category->getAllChildren());
            } else {
                $categoryLimit = $category->getId();
            }

then I used that list in the following query to get the product collection.

$productCollection = Mage::getResourceModel('catalog/product_collection')
                        ->setStoreId(0)
                        ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id=entity_id', null, 'left')
                        ->addAttributeToFilter('category_id', array('in' => $categoryLimit))
                        //->addAttributeToSelect('*')
                        ->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                        ->addAttributeToFilter('type_id', 'configurable');
                $productCollection->getSelect()->group('product_id')->distinct(true);
                $productCollection->load();

you will need to adjust the ->setStoreId(0) value.