Question

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();

    }
?>
Was it helpful?

Solution

$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

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top