Select sub-categories of a specific category of a product in Magento 1.9
-
21-01-2021 - |
Question
I am trying to write code for generating Google shopping feed in Magento 1.
I want to get categories assigned to a product which are subcategories of a specific category (Designers).
How do I do this?
I want to populate this in the brand tag in the XML and we do not have any manufacturers but store them in categories with a parent category called 'Designers'
Solution
You can manage to work by following code:
$designer_cat_id = 'YOUR DESIGNER CATEGORY ID';
$brands = array();
$categoryIds = $product->getCategoryIds();
if ($categoryIds)
{
$categoryCollection = Mage::getModel('catalog/category')->getCollection();
$categoryCollection->addAttributeToFilter('parent_id',['eq'=>$designer_cat_id]);
$categoryCollection->addIdFilter($categoryIds);
$categoryCollection->addNameToResult();
if ($categoryCollection->getSize() > 0)
{
foreach ($categoryCollection as $cat)
{
$cat_name = $cat->getName();
$url = $cat->getUrl();
// Write your code for xml node creation
}
}
}
This code is not tested. This is basically an idea.
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange