Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the category ids that a product is in with respect to the store that I'm currently on

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?

like image 785
Richard Housham Avatar asked Dec 20 '22 08:12

Richard Housham


1 Answers

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.

like image 133
Vinai Avatar answered Mar 04 '23 10:03

Vinai