1

I have product object & i get category ids using

$category_id = $product->getCategoryIds();

I need the collection for the category ids which i get in $category_id What will be the best & optimized way to get it in (block or helper or model) ?

Thanks

1
1

You can use the category collection factory for getting the category.

public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
    ) {
            $this->_categoryCollectionFactory = $categoryCollectionFactory;
            parent::__construct($context, $data);
    }

public function getCategoryCollection()
    {
        $categoryIds = $product->getCategoryIds();

        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToFilter('entity_id', $categoryIds);
    }

Let me know still if you face any queries.

Thanks

3
  • Thanks for the answer, will i get category name also on $collection->getName() ? – devhs Feb 26 at 5:47
  • Yes definitely. You can also refer to this blog: mageplaza.com/devdocs/… – ZealousWeb Feb 26 at 5:47
  • @dev if the answer is helpful then please upvote it. – ZealousWeb Feb 26 at 5:51
0

1)Create a Block and add following code:

<?php
namespace vendor\Category\Block;

class Category extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
        array $data = []
    ) {
        $this->categoryRepository = $categoryRepository;
        parent::__construct($context, $data);
    }

    /* $categoryId as category id */
    public function getCategoryById($categoryId){
        try {
            return $category = $this->categoryRepository->get($categoryId);
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            return ['response' => 'Category Not Found'];
        }
    }
}

2)Create custom template and add following code:

$categoryId = 5; // category id
$getCategory = $block->getCategoryById($categoryId);
echo $getCategory->getName();echo "<br>";
echo $getCategory->getUrlKey();echo "<br>";
echo $getCategory->getIsActive();echo "<br>";
echo "<pre>";print_r($getCategory->getData());

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.