Magento 2.3在.phtml文件中获取自定义分类属性失败问题
解决Magento自定义分类属性单个分类页面无法获取值的问题
问题原因
从registry获取的current_category对象属于精简加载状态,仅包含默认核心属性,未加载自定义的title_description属性;而分类集合查询时会自动包含已配置的自定义属性,因此集合页面能正常取值。
解决方案
方案1:在Block中手动加载自定义属性
修改你的Block方法,返回分类对象前手动加载目标属性或重新加载分类:
public function getCurrentCategory() { $currentCategory = $this->registry->registry('current_category'); if ($currentCategory) { // 方式1:仅加载需要的自定义属性(性能更优) $currentCategory->loadAttribute('title_description'); // 方式2:重新加载整个分类对象(加载所有属性) // $currentCategory->load($currentCategory->getId()); } return $currentCategory; }
方案2:使用CategoryRepository获取完整分类对象
通过Magento分类仓储类获取完整分类实例,默认会加载所有属性:
- 在Block构造方法中注入
CategoryRepositoryInterface:
protected $categoryRepository; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Registry $registry, \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository, array $data = [] ) { $this->categoryRepository = $categoryRepository; parent::__construct($context, $registry, $data); }
- 修改
getCurrentCategory方法:
public function getCurrentCategory() { $currentCategory = $this->registry->registry('current_category'); if ($currentCategory) { try { $currentCategory = $this->categoryRepository->get($currentCategory->getId()); } catch (\Exception $e) { // 可添加异常日志记录逻辑 } } return $currentCategory; }
额外检查项
- 确认自定义属性的作用域设置正确,对应店铺视图下已保存属性值
- 修改代码或属性设置后,执行缓存清理命令:
bin/magento cache:clean bin/magento cache:flush
内容的提问来源于stack exchange,提问作者Akhilesh
相关产品推荐
相关产品推荐

