I've followed a tutorial found here: https://webkul.com/blog/add-custom-image-attribute-category-magento-2/
With a slight modification which can be found in the InstallData, where I specified 'visible_on_front' :
<?php
namespace Vendor\Module\Setup;
use \Magento\Framework\Setup\ModuleContextInterface;
use \Magento\Framework\Setup\ModuleDataSetupInterface;
use \Magento\Framework\Setup\InstallDataInterface;
use \Magento\Eav\Setup\EavSetup;
use \Magento\Eav\Setup\EavSetupFactory;
use \Magento\Catalog\Setup\CategorySetupFactory;
class InstallData implements InstallDataInterface
{
protected $_eavSetupFactory;
protected $_categorySetupFactory;
public function __construct(
EavSetupFactory $eavSetupFactory,
CategorySetupFactory $categorySetupFactory
) {
$this->_eavSetupFactory = $eavSetupFactory;
$this->_categorySetupFactory = $categorySetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->_categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
\Magento\Catalog\Model\Category::ENTITY, 'grid_image', [
'type' => 'varchar',
'label' => 'Grid Image',
'input' => 'image',
'visible_on_front' => true,
'backend' => 'Magento\Catalog\Model\Category\Attribute\Backend\Image',
'required' => false,
'sort_order' => 9,
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
'group' => 'Content',
]
);
}
}
However, I am unable to access the actual attribute in the frontend. I'm grabbing the current category via the Registry, and find that the attribute simply isn't attached (tried checking using $category->debug()). Any ideas for how I can get access to it on the frontend?
-
Do you need an image on the catalog?Andrey Rad– Andrey Rad2019年04月17日 07:46:56 +00:00Commented Apr 17, 2019 at 7:46
1 Answer 1
You can add this code in your PHTML File.And get them your grid_image in frontend.
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$mediaUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$categoriesid = ['your category id'];
$imghelper = $this->helper('Magento\Catalog\Helper\Output');
?>
<?php foreach ($categories as $category) : ?>
<?php $homeimg = $category->getGridImage();
if ($homeimg) : ?>
<div class="box-inner">
<div class="homepage-category-img">
<div class="category-image-extra">
<img src="<?php echo $imghelper->resize($homeimg,420) ?>" alt="<?php echo $category->getName(); ?>">
</div>
</div>
<?php endif; ?>
<?php endforeach; ?>
Explore related questions
See similar questions with these tags.