Question

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

Was it helpful?

Solution

you can try like this:

 <?php
        $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()                              
        ->addAttributeToSelect('*')
        ->addFieldToFilter('entity_id', array('in' => $categoryIds));
                  
    foreach ($categories as $category) {
        echo $category->getName() . '<br>';
    }
    
    } 
    
    ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top