0

I am trying to get the category image from the below code

      $collection = $this->_categoryCollectionFactory->create();
      $collection->addAttributeToSelect('name','image')
                ->addAttributeToFilter('is_popular', array('eq' => 1))
               ->addAttributeToFilter('is_active',array('eq' => 1))
               ->addAttributeToSort('category_sort_no', 'ASC')
               ->setPageSize(12)
               ->load();

and i am looping through these but i am not getting category image.I can get category id from the collection and load the category object and get the image.But it is affecting the performance like below:

$category = $objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
$imgUrl = $category->getImageUrl();

Is there any way we can fetch the category image from the collection object?

Thanks!

0

You may try the steps descriibe blow

step 1) In template phtml file

<?php foreach ($collection as $category):
    $categoryImageUrl = $block->getThumbnailUrl($category->getThumbnail());
 ?>
      <img src="<?php echo $categoryImageUrl;?>" alt="<?php echo $category->getName() ?>" title="<?php echo $category->getName() ?>" />
<?php endforeach;?>

Step 2) In php block class file:

......................
......................
protected $_storeManager;

public function __construct(
 Context $context, 
 StoreManagerInterface $storeManager)
    {
        ......................
        $this->_storeManager = $storeManager;        
        parent::__construct($context);
    }

public function getThumbnailUrl($imageName){
        $url = $this->_storeManager->getStore()->getBaseUrl(
                \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
            ) . 'catalog/category/' . $imageName;
        return $url;
    }
......................
......................
1
  • I am trying to get image but not thumbnail image – venki Jun 1 '20 at 9:53

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.