0

I want to display the category image in mega menu(which we have created using html) but not success.

I have no idea, how to make this work so I'm here and hoping someone can help me with this.

Below is my code for your reference:

Code in phtml file:

<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
?>
<?php
/**
* Top menu for store
*
* @var $block \Magento\Theme\Block\Html\Topmenu
*/
?>
<link rel="stylesheet" type="text/css" href="<?php echo $block->getViewFileUrl('css/cart.css')?>">
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
?>
<?php
/**
* Top menu for store
*
* @var $block \Magento\Theme\Block\Html\Topmenu
*/
?>
<header class="headers">
  <div class="header-inrs">
    <div class="menu-container">
      <div class="menus contenedor-menu">
        <ul class="clearfix backcolor designmenu">
          <div class="totalmobilelog">
            <div class="lo">
              <a href="" >
                <b class="clsml">
                  <i class="fa fa-user-plus" aria-hidden="true">
                  </i>Login
                </b>
              </a>
            </div>
            <div class="si">
              <a href="" >
                <b class="clsml">
                  <i class="fa fa-registered" aria-hidden="true">
                  </i>Sign Up
                </b>
              </a>
            </div>
          </div>
          <?php
$categories = $block->getStoreCategories();
foreach ($categories as $category):
?>
          <li>
            <a href="<?php echo $category->getRequestPath();?>">
              <?php echo $category->getName(); ?>
            </a>
            <ul class="subc">
              <?php
$subCategories = $block->getCategoryById($category->getId());
foreach ($subCategories->getChildrenCategories() as $subCategory):
?>
              <li>
                <a href="<?php echo $subCategory->getRequestPath();?>">
                  <?php echo $subCategory->getName(); ?>
                  <?php echo $category->getImageUrl(); ?>
                </a>
              </li>
              <?php endforeach; ?>
            </ul>
            <?php echo $block->getSubcategories($subCategories); ?>
            <?php endforeach; ?>
          </li>
        </ul>
      </div>
    </div>
  </div>
</header>

Code in Block file:

<?php
namespace Butterfly\Megamenu\Block;
class Categorylist extends \Magento\Framework\View\Element\Template
{    
protected $_categoryHelper;
protected $categoryFactory;
protected $_catalogLayer;
protected $_categoryRepository;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,     
\Magento\Catalog\Helper\Category $categoryHelper,        
\Magento\Catalog\Model\CategoryRepository $categoryRepository,        
array $data = []
) {
$this->_categoryHelper = $categoryHelper;   
$this->_categoryRepository = $categoryRepository;
parent::__construct(
$context,          
$data
);
}
public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
{
return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
}
public function getCategoryById($categoryId) 
{
return $this->_categoryRepository->get($categoryId);
}
public function  getSubcategories($categories) {
$array= '<ul class="child">';
foreach($categories->getChildrenCategories() as $category) {
$array .= '<li>'.
'<a href="' .$category->getRequestPath().'">' .
$category->getName() . "</a>\n";
if($category->hasChildren()) {
$children = $this->getCategoryById($category->getId());
$array .=  $this->getSubcategories($children);
}
$array .= '</li>';
}
return  $array . '</ul>';
}
}

1.enter image description here

  1. enter image description here
  • have you got solution? – Ronak Chauhan Oct 1 '19 at 8:19
  • @RonakChauhan, No, still I'm looking for the solution. Can you please help me with that. – Siva Oct 1 '19 at 8:36
  • it's simple, you can have category image with $category object so use it below category name – Ronak Chauhan Oct 1 '19 at 9:08
  • @RonakChauhan, Can you please elaborate what you're trying to explain? Please give me example snippet – Siva Oct 1 '19 at 9:58
0

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'); ?>" />
  • I have tried this but not working. You can see in my code, I have put <?php echo $category->getImageUrl(); ?> – Siva Oct 1 '19 at 7:02
  • Try to above code for get category image I hope it's work for you – Baharuni Asif Oct 1 '19 at 7:30
0

Method 1

Magento core function is available in \Magento\Catalog\Model\Category file and it is called getImageUrl, code snippet can be seen below -:

/**
 * Get image url by attribute code.
 *
 * @param string $attributeCode
 * @return string
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function getImageUrl($attributeCode = 'image')
{
    $url = false;
    $image = $this->getData($attributeCode);
    if ($image) {
        if (is_string($image)) {
            $url = $this->_storeManager->getStore()->getBaseUrl(
                \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
            ) . 'catalog/category/' . $image;
        } else {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('Something went wrong while getting the image url.')
            );
        }
    }

    return $url;
}

If you are using your own class then you need to add \Magento\Catalog\Model\CategoryFactory $categoryFactory in the constructor and call the function below to get full category image path

$category = $this->categoryFactory->create()->load($categoryId);
$fullCategoryPath = $category->getImageUrl();
echo $fullCategoryPath

Method 2

If you already have category image name then you can write your own function to return full category image path using the following snippet

/**
  * Get image url by imagename.
  *
  * @param string $image
  * @return string
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 protected function getImageUrl($image)
 {
     $url = $image;
     if ($image) {
         if (is_string($image)) {
             $url = $this->storeManager->getStore()->getBaseUrl(
                     \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
                 ) . 'catalog/category/' . $image;
         } else {
             throw new \Magento\Framework\Exception\LocalizedException(
                 __('Something went wrong while getting the image url.')
             );
         }
     }

     return $url;
 }

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

0

Block file:

<?php
namespace Butterfly\Megamenu\Block;
class Categorylist extends \Magento\Framework\View\Element\Template
{    
protected $_categoryHelper;
protected $categoryFactory;
protected $_catalogLayer;
protected $_categoryRepository;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,     
\Magento\Catalog\Helper\Category $categoryHelper,        
\Magento\Catalog\Model\CategoryRepository $categoryRepository,        
array $data = []
) {
$this->_categoryHelper = $categoryHelper;   
$this->_categoryRepository = $categoryRepository;
parent::__construct(
$context,          
$data
);
}
public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
{
return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
}
public function getCategoryById($categoryId) 
{
return $this->_categoryRepository->get($categoryId);
}
public function  getSubcategories($categories) {
$array= '<ul class="child">';
foreach($categories->getChildrenCategories() as $category) {
$array .= '<li>'.
'<img src="'. $category->getImageUrl() . '" alt="Smiley face" height="42" width="42"><a href="' .$category->getRequestPath().'">' .
$category->getName() . "</a>\n";
if($category->hasChildren()) {
$children = $this->getCategoryById($category->getId());
$array .=  $this->getSubcategories($children);
}
$array .= '</li>';
}
return  $array . '</ul>';
}
}

Check this code and try to get imageUrl.

  • Thanks, I have tried as you suggested and it seems working. Please see attached screenshot. But I want to show the image as per in the second screenshot. To do that I have to put the same code in phtml file. Am I right? – Siva Oct 1 '19 at 10:18
  • No, I don't think you need to change in phtml file, Block file will work, just place image at correct place in <li> element – Ronak Chauhan Oct 1 '19 at 10:22
  • Ok. Let me try. I have uploaded category image but still I can only see the alt text instead of image. Where am I wrong? – Siva Oct 1 '19 at 10:27
  • Also, I'm getting "Unknown image src" in console so that I'm not getting the image instead I'm getting only the alt text. – Siva Oct 1 '19 at 11:32
  • try with this: $category->getImageUrl('category_alternate_image') – Ronak Chauhan Oct 1 '19 at 12:22

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.