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

    }
?>

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

2
  • Thank you. Now it works. Oct 8, 2020 at 5:49
  • +1 please approve answer if its work Oct 8, 2020 at 6:15

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.