We have created a megamenu and want to load the category image on the menu. I'm not sure how to load that.
As of now, we have just hardcoded the image.
Below is the code:
<?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, $parent= '') {
$i = 0;
$array= '<ul class="child">';
foreach($categories->getChildrenCategories() as $category) {
$array .= '<li>';
$cat_image = 'https://techcrunch.com/wp-content/uploads/2010/10/pirate.jpg?w=990&crop=1';
if($i == 3 && $parent == '' && $cat_image != ""){
$array .= '<img class="u_cat_image" src="'.$cat_image.'" />';
$array .= '</li><li>';
}
$array .= '<a href="/newmagento/' .$category->getRequestPath().'">' .
$category->getName() . "</a>\n";
if($category->hasChildren()) {
$children = $this->getCategoryById($category->getId());
$array .= $this->getSubcategories($children, 'child');
}
$array .= '</li>';
$i++;
}
return $array . '</ul>';
}
}
Any help will be appreciated!
I can see the category images in DB: