I'm on a product page and have the product object but when I try to get the category ids using:
$_product->getCategoryIds();
or:
$_product->getResource()->getAttribute('category_ids')->getFrontend()->getValue($_product);
it gets me all the category ids and I just want the ones for the store I'm on.
It's a multistore environment so hence my problem. Everything else seems ok and the category list works fine. This is my only problem. Can anyone help?
Pretty similar to Alans answer, maybe a bit less looping:
$rootCategory = Mage::getModel('catalog/category')
->load(Mage::app()->getStore()->getRootCategoryId());
$sameStoreCategories = Mage::getResourceModel('catalog/category_collection')
->addIdFilter($product->getCategoryIds())
->addFieldToFilter('path', array('like' => $rootCategory->getPath() . '/%'))
->getItems();
var_dump(array_keys($sameStoreCategories));
This will always work. The ugly thing is that you still need to load the categories.
Here is a variation you can use if the flat category tables are enabled:
$sameStoreCategories = Mage::getResourceModel('catalog/category_flat_collection')
->addIdFilter($product->getCategoryIds())
->getItems();
var_dump(array_keys($sameStoreCategories));
Why does it work? Because the flat tables are indexed by store, and each flat table only contains the category entity records that are associated with that store groups root category.
So even though you are filtering by all category IDs associated with the product, the collection will only contain the categories present in the current store.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With