How I can get categories for related products like in the following image:

enter image description here

I use this code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
echo $category->getName();

in the Magento_Catalog/templates/product/list/items.phtml file but it display the category of the current product not the related products category.

Or maybe I can find a module with this functionality?

Thank you


you can try like this:

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $currentProduct = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product information
        $id = $currentProduct->getId();
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($id);
    $relatedProducts = $product->getRelatedProducts();
    if (!empty($relatedProducts)) {
        echo 'Related Products <br />';
        $productid[] = '';   
        foreach ($relatedProducts as $relatedProduct) {
            $_product = $objectManager->create('Magento\Catalog\Model\Product')->load($relatedProduct->getId());
            $productid[] = $relatedProduct->getId();
    $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
    $collections = $productCollection->addAttributeToSelect('*')
                    ->addFieldToFilter('entity_id', array('in' => $productid));
    $categoryIds[] = '';
    foreach ($collections as $collection) {
        $categoryIds[] = $collection->getCategoryIds();
    $categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
    $categories = $categoryFactory->create()                              
        ->addFieldToFilter('entity_id', array('in' => $categoryIds));
    foreach ($categories as $category) {
        echo $category->getName() . '<br>';
  • Thank you very much for your help ...
    – Robert
    Feb 3 '21 at 10:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.