How to Get Related Products Collection in Magento 2?

Magento 2, one of the leading e-commerce platforms, empowers online retailers with a plethora of features to create a dynamic and engaging shopping experience for their customers. One such feature that significantly contributes to this experience is the ability to showcase related products. In this comprehensive guide, we will walk through the process of obtaining the related products collection in Magento 2 programmatically, providing a deeper understanding of the underlying mechanisms.

Understanding Related Products in Magento 2
Before delving into the technical details, it's essential to grasp the concept of related products in Magento 2. Related products are items that are associated with or complement the product a customer is currently viewing. These can include accessories, add-ons, or products from the same category that might interest the shopper. Magento 2 provides a versatile system for managing related products, allowing merchants to manually select them or use predefined rules for automatic association.

To get related product collection in Magento 2:

1. Create RelatedProducts.php file at app/code/Vendor/Extension/Block folder

<?php
namespace Vendor\Extension\Block;

use Magento\Framework\View\Element\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Registry;

class RelatedProducts extends Template
{
    protected $registry;
    
    public function __construct(
        Context $context,        
        Registry $registry,
        array $data = []
    )
    {        
        $this->registry = $registry;
        parent::__construct($context, $data);
    }
    
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
    
    public function getCurrentProduct()
    {        
        return $this->registry->registry('current_product');
    }    
    
}

2. Call the below function in your phtml file

$currentProduct = $block->getCurrentProduct();
 
if ($currentProduct = $block->getCurrentProduct()) {
    $relatedProducts = $currentProduct->getRelatedProducts();
    
    if (!empty($relatedProducts)) {
        foreach ($relatedProducts as $relatedProduct) {
            echo $relatedProduct->getName().'<br>';
        }
    }    
}

By understanding the steps involved in obtaining and displaying related products programmatically, you can leverage this feature to its full potential, offering customers a personalized and engaging shopping journey that can ultimately lead to increased sales and satisfaction.