Today, we’re going to teach you guys how to get related products collection in Magento 2 store.

Related products collection basically share the same category or group as the main product page.

They help store owners to encourage their customers to purchase those related products and increase the average order value.

As a result, It boosts the conversion rate that positively affects the overall sales and revenue of a Magento 2 store.

Below, we have shared the complete step-by-step process to get related products collection in Magento 2.

Steps to Get Related Products Collection in Magento 2

First of all, create an Extension.php file in the app/code/Vendor/Extension/Block directory and copy the following code.

<?php
namespace Vendor\Extension\Block;
use Magento\Framework\View\Element\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Registry;
class Extension 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');
   }      
}

 

After that, we need to call a function in the pHTML file by copying the following code:

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

Conclusion

And that’s it! - This is the step-by-step process to get related products collection in Magento 2 store.

Alternatively, you can also follow this guide on How to Configure Automatic Related Products in Magento 2  to get related products collection and display the right related products on each product detail page based on your customers’ behavior.

And if you need our professional assistance, feel free to contact us anytime.

Also read: