0

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

1 Answer 1

1

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>';
    }
    
    } 
    
    ?>
1
  • Thank you very much for your help ...
    – Robert
    Commented Feb 3, 2021 at 10:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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