Skip to content

Instantly share code, notes, and snippets.

@antoinekociuba
Last active February 24, 2022 09:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoinekociuba/435f0c8c1881e98e27b0fed527ba8ea7 to your computer and use it in GitHub Desktop.
Save antoinekociuba/435f0c8c1881e98e27b0fed527ba8ea7 to your computer and use it in GitHub Desktop.
Magento 1 - Get array of all category trees for a given product
<?php
// Get all product category IDs
$categoryIds = $product->getCategoryIds();
// Get category trees, filtered by product category IDs
$helper = Mage::helper('catalog/category');
$categoryTreeCollection = $helper->getStoreCategories('path', true, false);
$categoryTreeCollection->addAttributeToFilter('entity_id', ['in' => $categoryIds]);
$categoryTrees = [];
foreach ($categoryTreeCollection as $category) {
// Top level categories first
if ($category->getLevel() == 2) {
$categoryTrees[$category->getPath()][] = $category->getName();
} else {
// Sub level categories then
foreach ($categoryTrees as $key => $value) {
if (strpos($category->getPath(), $key) !== false) {
$categoryTrees[$key][] = $category->getName();
}
}
}
}
// At the end, you get an array of product trees. You can loop through it, and do whatever you need with it
Array
(
[1/2/10] => Array
(
[0] => Category A level 1
)
[1/2/20] => Array
(
[0] => Category B level 1
[1] => Category C level 2
[2] => Category D level 3
)
[1/2/30] => Array
(
[0] => Category E level 1
[1] => Category F level 2
[2] => Category G level 3
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment