【问题标题】:How to get category collection using product id in product details page in Magento 2如何在 Magento 2 的产品详细信息页面中使用产品 ID 获取类别集合
【发布时间】:2016-05-13 14:18:05
【问题描述】:

如何在产品详情页面获取分类集合?我试过使用下面的代码,但它没有得到集合。

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')
    ->registry('current_category');
$categoryProducts = $category->getCategoryProducts($categoryId);

【问题讨论】:

    标签: php magento2


    【解决方案1】:

    在产品详情页面上,您可以在产品的 Object 上调用 getCategoryCollection 函数来获取类别集合,如下所示:

    $_product = $block->getProduct();
    $categoryCollection = $_product->getCategoryCollection();
    

    【讨论】:

    • 您还可以将类别属性添加到集合中-$_product->getCategoryCollection()->addAttributeToSelect(array('name'))
    • 这个工作正常,但是从首页直接进入产品就不行了。不是通过类别页面。
    【解决方案2】:

    从您发布的代码中,您使用 $categoryId 但它未定义。

    试试:

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
    $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category'); 
    $categoryProducts = $category ->getCategoryProducts($category->getId());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多