当前位置: 技术文章>> 如何在Magento 2中获取特定类别的所有子类别ID?

文章标题:如何在Magento 2中获取特定类别的所有子类别ID?
  • 文章分类: Magento
  • 22197 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


要获取类别 ID,请执行以下步骤。

第 1 步:在以下路径的 Magento 根目录中创建一个文件

magento_root_directory\getcategory.php

然后添加代码,如下所示。

<?php
 
use Magento\Framework\AppInterface;
ini_set('display_errors', TRUE);
try
{
    require_once __DIR__ . '/app/bootstrap.php';
}
catch (\Exception $e)
{
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
 
try
{
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');
   
    $categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');// Instance of Category Model
    $rootCategoryId = 2; // your root category Id
    $category = $categoryFactory->create()->load($rootCategoryId);
    $categoryIds= $category->getAllChildren(false);
    echo $categoryIds; //will return comma separated list of ids
}
catch (Exception $e)
{
    echo $e->getMessage();
}
 
?>

输出:

上面的代码将返回如下结果。

类别编号

结论:

希望您将能够在Magento 2中获取特定类别的所有子类别ID。


推荐文章