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

Magento 2获取商品分类路径名称并排除根分类求助

解决方案

问题分析

你当前的代码存在两个核心问题:

  1. 使用$cat->getPath()获取的是分类ID组成的路径,而非分类名称
  2. 未实现排除根分类(ID=1)的逻辑

修正后的代码(模板/临时场景适用)

<?php
$categories = $product->getCategoryIds();
$categoryPaths = [];

foreach ($categories as $categoryId) {
    // 获取当前分类对象
    $category = $objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
    // 拆分分类路径的ID数组,比如把"1/3/1945"拆成["1","3","1945"]
    $pathIds = explode('/', $category->getPath());
    // 移除根分类ID(数组第一个元素)
    array_shift($pathIds);
    
    $categoryNames = [];
    foreach ($pathIds as $id) {
        // 获取每个层级分类的名称
        $levelCategory = $objectManager->create('Magento\Catalog\Model\Category')->load($id);
        $categoryNames[] = $levelCategory->getName();
    }
    
    // 用/拼接成单条分类名称路径
    $categoryPaths[] = implode('/', $categoryNames);
}

// 用%%分隔所有分类路径
$categoryList = implode(' %% ', $categoryPaths);
echo $categoryList;

性能优化版本(生产环境推荐)

直接循环load分类对象会重复发起数据库查询,性能较差,推荐通过分类集合批量获取名称:

<?php
$categories = $product->getCategoryIds();
$categoryPaths = [];

// 收集所有需要查询的分类ID(含各层级)
$allCategoryIds = [];
foreach ($categories as $categoryId) {
    $category = $objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
    $pathIds = explode('/', $category->getPath());
    array_shift($pathIds);
    $allCategoryIds = array_merge($allCategoryIds, $pathIds);
}
$allCategoryIds = array_unique($allCategoryIds);

// 批量查询分类名称,减少数据库请求
$categoryCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\Collection')
    ->addFieldToFilter('entity_id', ['in' => $allCategoryIds])
    ->addAttributeToSelect('name');

// 构建分类ID到名称的映射数组
$categoryNameMap = [];
foreach ($categoryCollection as $cat) {
    $categoryNameMap[$cat->getId()] = $cat->getName();
}

// 生成最终的分类名称路径
foreach ($categories as $categoryId) {
    $category = $objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
    $pathIds = explode('/', $category->getPath());
    array_shift($pathIds);
    
    $names = [];
    foreach ($pathIds as $id) {
        $names[] = $categoryNameMap[$id] ?? '';
    }
    $categoryPaths[] = implode('/', $names);
}

$categoryList = implode(' %% ', $categoryPaths);
echo $categoryList;

输出示例

最终会得到类似这样的结果:

数码产品/手机 %% 数码产品/手机/智能手机 %% 数码配件/充电设备

内容的提问来源于stack exchange,提问作者G. G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 02:13:17