Magento 2.2.7
I have to output category name and "tree" or path for product.
For instance if my product is in category Lg775
my output should be:
Hardware/Motherboards/Intel/Lg775
so far I have this code that gives me category ID:
//Load the product categories
$categories = $product_data->getCategoryIds();
//Select the last category in the list
$categoryId = end($categories);
Thank you all Magento experts for all the help so far! I really appreciate it :)
UPDATE - Solved
So I used the answer I checked however I had to modify the code so here is my code how to get full category path for "categoryID"
<?php
namespace Vendor\Module\Helper;
class CategoryTree {
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
private $storeManager;
/**
* @var \Magento\Catalog\Api\CategoryRepositoryInterface
*/
private $categoryRepository;
/**
* @var \Magento\Catalog\Model\ResourceModel\Category\Tree
*/
private $tree;
public function __construct(
\Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
\Magento\Catalog\Model\ResourceModel\Category\Tree $tree,
\Magento\Store\Model\StoreManagerInterface $storeManager) {
$this->tree = $tree;
$this->categoryRepository = $categoryRepository;
$this->storeManager = $storeManager;
} // end of function __construct
public function getTreeByCategoryId($categoryId)
{
$storeId = $this->storeManager->getStore()->getId();
$category = $this->categoryRepository->get($categoryId, $storeId);
$categoryTree = $this->tree->setStoreId($storeId)->loadBreadcrumbsArray($category->getPath());
$categoryTreepath = array();
foreach($categoryTree as $eachCategory){
echo $eachCategory['name'];
$categoryTreepath[] = $eachCategory['name'];
}
$categoryTree = implode(" > ",$categoryTreepath);
return $categoryTree;
} // end of function getTreeByCategoryId
} // end of class
later I called that class like this:
$categoryObject=\Magento\Framework\App\ObjectManager::getInstance();
$category=$categoryObject->create('Vendor\Module\Helper\CategoryTree');
$categoryTreepath=$category->getTreeByCategoryId($categoryId);
var_dump($categoryTreepath);
The result was just what I needed :) Thank you all!