1

I want to get all categories name and image URL(to show image) to show on the storefront but when I am using function getImageUrl() and getImage() returns nothing. Why this is happening can anyone help me?.I am using Magento 2.3.5 -p1 version. I am using the following code for block-

<?php
namespace Demo\GetAllCategories\Block;
class DisplayAllCategory extends \Magento\Framework\View\Element\Template {
 protected $_categoryHelper;
 protected $categoryFactory;
 protected $_catalogLayer;
 public function __construct(
 \Magento\Catalog\Block\Product\Context $context, 
 \Magento\Catalog\Helper\Category $categoryHelper, 
 array $data = []
 ) {
 $this->_categoryHelper = $categoryHelper; 
 parent::__construct(
 $context, 
 $data
 );
 }
 /**
 * Retrieve current store level 2 category
 *
 * @param bool|string $sorted (if true display collection sorted as name otherwise sorted as based on id asc)
 * @param bool $asCollection (if true display all category otherwise display second level category menu visible category for current store)
 * @param bool $toLoad
 */
 public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
 {
 return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
 }
}

Phtml code-

<?php
 $categorys = $this->getStoreCategories(false,false,true);
 
 
 foreach($categorys as $category){
 echo $category->getName();
 ?>
 <br>
 <?php
 echo $category->getId();
 ?>
 <br>
 <?php
 echo $category->getImageUrl();
 ?>
 <br>
 <?php
 echo $category->getUrl();
 }
?>
asked Oct 7, 2020 at 15:43

1 Answer 1

2

$category->getImageUrl() is a right code to get image url of the category.

But you have to load that data from category model factory of as per below.

$category = $objectManager->get('Magento\Catalog\Model\CategoryFactory')->create()->load($cat_id);
$category->getImageUrl();

Use dependency injection instead of objectmanager.

If this help then hit LIKE :).

Enjoy your coding !!! :)

Thank you
Hiren Patel

answered Oct 7, 2020 at 15:54
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.