You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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分类仓储类获取完整分类实例,默认会加载所有属性:

  1. 在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);
}
  1. 修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 21:25:43