6

I want to display the category image of the category.I have a phtml file and is called in cms home page.

<?php 
$subcats = array(99,189);
$imageBlock = $block->getLayout()->createBlock('Magento\Catalog\Block\Category\ListProduct');

foreach($subcats as $cat_id){
    //echo $cat_id;
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->create('Magento\Catalog\Model\Category')->load($cat_id);
    $categoryImage = $imageBlock->getImage($category, 'category_page_list');
    echo 'dfdf'.$category->getName();
    //$productImage = $imageBlock->getImage($category);
    echo 'ssds'.$categoryImage;

}

But it is not displaying the image and getting an error.

Please help.

1
  • Maybe you should add the text of the error you get? Commented Mar 28, 2017 at 8:40

7 Answers 7

7

I have Used This code to get Category images in my code Please look at these

<?php
    $category = $this->_objectManager->create('Magento\Catalog\Model\Category')->load($item->getId());
    $_outputhelper    = $this->helper('Magento\Catalog\Helper\Output');
    $_imgHtml   = '';
    if ($_imgUrl = $category->getImageUrl()) {
        $_imgHtml = '<img src="' . $_imgUrl . '" />';
        $_imgHtml = $_outputhelper->categoryAttribute($category, $_imgHtml, 'image');
        /* @escapeNotVerified */ echo $_imgHtml;
    }
?>
3
  • yup absolutely.it is working code @aravind Commented Jan 23, 2018 at 5:28
  • @PranayK How can i get products images using sku?
    – Gem
    Commented May 14, 2018 at 8:37
  • @Learing_Coder, I'm struggling in getting the category image, Can you please help me? I have tried your code in phtml file but it's not working as expected.
    – Siva
    Commented Oct 3, 2019 at 6:43
3

You can use this code. just pass the category id fetch the image

use Magento\Catalog\Model\CategoryRepository;

public function getCategoryImage($categoryId)
{
    $categoryIdElements = explode('-', $categoryId);
    $category           = $this->categoryRepository->get(end($categoryIdElements));
    $categoryImage       = $category->getImageUrl();

    return $categoryImage;
}
3

To get Category Image url:

<?php echo $category->getImageUrl(); ?>

And use it in <img> tag like

<img src="<?php  echo $category->getImageUrl(); ?>" />

And get Alternate Image url:

echo $category->getImageUrl('category_alternate_image'); 
<img src="<?php  echo $category->getImageUrl('category_alternate_image'); ?>" />
1

View Modal (CategoryList.php)

use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\Block\ArgumentInterface;

class CategoryList implements ArgumentInterface
{
    /**
     * @var CollectionFactory
     */
    private $categoryFactory;
    /**
     * @var Category
     */
    private $category;

    public function __construct(
        CollectionFactory $categoryFactory,
        Category $category
    ) {
        $this->categoryFactory = $categoryFactory;
        $this->category = $category;
    }

    /**
     * @return array
     */
    public function getList()
    {
        $collection = $this->categoryFactory->create();
        $items = [];
        $collection->addFieldToFilter('is_active', ['eq' => 1]);
        foreach ($collection as $key => $categoryData) {
            /** @var \Magento\Catalog\Model\Category $category */
            try {
                $category = $this->category->load($categoryData->getID());
                $items[$key]['image'] = $category->getImageUrl();
                $items[$key]['name'] = $category->getName();
            } catch (LocalizedException $e) {
            }
        }
        return $items;
    }
}

in your_layout.xml file

<block class="Magento\Framework\View\Element\Template" template="Vendor_Module::template.phtml">
    <arguments>
        <argument name="category_list" xsi:type="object">\Ktpl\CategoryCms\ViewModel\CategoryList</argument>
    </arguments>
</block>

in your template.phtml file

<?php

/** @var $viewModel \Ktpl\CategoryCms\ViewModel\CategoryList */

$viewModel = $block->getCategoryList();
$categories = $viewModel->getList();

?>
<div class="home-cat-wrap">
    <div class="category">
        <?php foreach ($categories as $category): ?>
            <div class="cat-item">
                <div class="cat-img">
                    <img src="<?= $category['image'] ? $category['image'] : "http://demo.link" ?>" alt="">
                </div>
                <h4><a href="#"><?= $category['name'] ?></a></h4>
            </div>
        <?php endforeach; ?>
    </div>
    <div class="view-more"><a class="action primary">View More Categories</a></div>
</div>
0

I think you are missing here to include helper, you need to use Magento\Catalog\Helper\Output helper. See this link for help. Click here and here to know. How to Create and Use Helpers in Magento 2?

0

[Magento 2.4.x]

You can use the below function to get the category media image URL.

/**
 * @category Msquare
 * @package Msquare_CategoryImageSlider
 * @author Mahesh Makwana <[email protected]>
 */

 ...............................................................
 ...............................................................
 ...............................................................

/**
 * @var \Magento\Catalog\Model\Category\Image
 */
protected $categoryImage;

/**
 * @var \Magento\Catalog\Model\Category\FileInfo
 */
protected $fileInfo;

/**
 * @var \Magento\Catalog\Helper\ImageFactory
 */
protected $imageHelperFactory;

/**
 * @var \Magento\Framework\View\Asset\Repository
 */
protected $assetRepository;

/**
 * @var \Magento\Catalog\Model\CategoryRepository
 */
protected $categoryRepository;

public function __construct(
    ...............................................................
    \Magento\Catalog\Model\CategoryRepository $categoryRepository,
    \Magento\Catalog\Model\Category\Image $categoryImage,
    \Magento\Catalog\Model\Category\FileInfo $fileInfo,
    \Magento\Catalog\Helper\ImageFactory $imageHelperFactory,
    \Magento\Framework\View\Asset\Repository $assetRepository,
    ...............................................................
) {
    ...............................................................
    $this->categoryRepository = $categoryRepository;
    $this->categoryImage = $categoryImage;
    $this->fileInfo = $fileInfo;
    $this->imageHelperFactory = $imageHelperFactory;
    $this->assetRepository = $assetRepository;
    ...............................................................
}

public function getCategoryImage($categoryData, $attributeCode)
{
    $imageLink = null;
    $fileName = $categoryData->getData($attributeCode);
    if (($fileName) && ($this->fileInfo->isExist($fileName))) {
        $imageLink = $this->categoryImage->getUrl($categoryData, $attributeCode); //get category image
    } else {
        $imageHelper = $this->imageHelperFactory->create();
        $imageLink = $this->assetRepository->getUrl($imageHelper->getPlaceholder('image')); // get default placeholder image
    }

    return $imageLink;
}

public function getCategoryData($categoryId)
{
  return $this->categoryRepository->get($categoryId);
}

After that you need to call the above function into your related phtml file like below:

$categoryData = $block->getCategoryData(4);
$categoryImage = $block->getCategoryImage($categoryData, 'image'); // you can also add your custom category image atribute
-3

I tried following so that it does not affect performance and you need to call the category model seprately

Open in root of magento 2.2

/vendor/magento/module-catalog/Model/ResourceModel/Category.php

On line750ish

Add

->addAttributeToSelect(
    'image'
)

or replace function

 /**
     * Return child categories
     *
     * @param \Magento\Catalog\Model\Category $category
     * @return \Magento\Catalog\Model\ResourceModel\Category\Collection
     */
    public function getChildrenCategories($category)
    {
        $collection = $category->getCollection();
        /* @var $collection \Magento\Catalog\Model\ResourceModel\Category\Collection */
        $collection->addAttributeToSelect(
            'url_key'
        )->addAttributeToSelect(
            'image'
        )->addAttributeToSelect(
            'name'
        )->addAttributeToSelect(
            'all_children'
        )->addAttributeToSelect(
            'is_anchor'
        )->addAttributeToFilter(
            'is_active',
            1
        )->addIdFilter(
            $category->getChildren()
        )->setOrder(
            'position',
            \Magento\Framework\DB\Select::SQL_ASC
        )->joinUrlRewrite();

        return $collection;
    }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.