0

Hi i want to load multiple categories in Magento 2.3. but it only fetch 1st category of a subcategory, not rest of category.

$categories = $_objectManager->create('Magento\Catalog\Model\Category')->load(3,4,5);
0

Try with below code to get of a subcategory to 1st level category

protected $_registry;

public function __construct(
    \Magento\Framework\Registry $registry,      
    \Magento\Framework\View\Element\Template\Context $context
) {
    $this->_registry = $registry;
    parent::__construct($context);
}

public function getCurrentCategory()
{
    return $this->_registry->registry('current_category');
}

public function getLevel1Category(){
    if($this->getCurrentCategory()){
        if($this->getCurrentCategory()->getParentCategories()){
            foreach ($this->getCurrentCategory()->getParentCategories() as $parent) {
                if ($parent->getLevel() == 1) {
                    // reurns the level 1 category id;
                    return $parent->getId();
                }
            }
        }
    }
    return null;
}
0

Always avoid use the ObjectManager directly on your code. You can use the below methods in your code to get the category and sub-categories data

protected $categoryRepository;

public function __construct(
    \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository
) {
    $this->categoryRepository = $categoryRepository;
}

public function getCategoryName()
{
    $categoryId = '43';
    $category = $this->_categoryFactory->create()->load($categoryId);
    $categoryName = $category->getName();
    return $categoryName;
}

For getting first level categories, you can use below code

$parent_category_id = 3;
$parentCategory = $this->categoryRepository->get($parent_category_id);
$subcategories = $parentCategory->getChildrenCategories();
foreach($subcategories as $subcategory) {
    echo $subcategory->getName();
}

For 2nd level categories, you can use below code

$parent_category_id = 3;
$parentCategory = $this->categoryRepository->get($parent_category_id);
$subcategories = $parentCategory->getChildrenCategories();
foreach($subcategories as $subcategory) {
    echo ' = '.$subcategory->getName().'<br/>';
    if($subcategory->hasChildren()) {
        $childCategoryObj = $this->categoryRepository->get($subcategory->getId());
        $childSubcategories = $childCategoryObj->getChildrenCategories();
        foreach($childSubcategories as $childSubcategory) {
            echo ' == '.$childSubcategory->getName().'<br/>';
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.