Today I want to quickly cover an area that I get asked about at least once a month, and that is “If a product belongs to more than one category.. how do I get the correct parent category while viewing a product through one category or the other?”.
With that said the, the biggest scenario for this need would be to determine the products parent category in order to perform something unique to the product’s page while viewing product’s page through one category or another.
This is a very simple method that assumes you have the product of question loaded up or rather, you are at the product level of your store in order to obtain some information about the products parent categories.
So here we go.
First you need to gather all the category id’s this product belongs to, so to do this we simply make a new variable called “$catIds” and gather all the category id’s like so:
Next we simply need to point to the first category in this new “$catIds” variable array like so:
(Remembere the number 0 is = 1 or rather first in an array.)
getCategoryIds(); $relativeCatId = $catIds; ?>
So now that we have gathered our relative parent category id, we can begin to load this category up in order to gather information from it and ultimately create a unique condition for our products page:
getCategoryIds(); $relativeCatId = $catIds; $category = Mage::getModel("catalog/category")->load($relativeCatId); ?>
Now that we have loaded up our relative parent category into this new variable called “$category” we can then say, “Grab the category’s name, or even attributes to create some kind of condition.”, like so:
getCategoryIds(); $relativeCatId = $catIds; $category = Mage::getModel("catalog/category")->load($relativeCatId); ?> getName() == "Category One"): ?> //DO THIS getName() == "Category Two"):?> //DO THAT
And that’s it!
So to recap, all we did was while under a product level, gathered all its parent category id’s into the variable “$catIds”. Once all category id’s we captured, we proceeded to highlight or rather grabbed our first category’s id from the array (0) and used it to load the category up. Once this category was loaded, we could access its attributes or information. We used the category’s information to build a condition and perform something unique to the product page depending on if its being viewed through one category or a completely different category.
Devin R. Olsen