How to Get Related Products Collection in Magento 2?

Related products are one of the most common ways to drive more sales in e-Commerce. You have to add related products manually or automatically through the related product rules to increase the average order value. But there is one more way. You can get related products collection in Magento programmatically. 

So if you want to avoid monotonous manual configuration of related products in Magento, keep reading.

To get related product collection in Magento 2: 

1. Create an Extension.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 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');
}

}

2. Call a function in the PHTML file.

$currentProduct = $block->getCurrentProduct();

if ($currentProduct = $block->getCurrentProduct()) {
    $relatedProducts = $currentProduct->getRelatedProductCollection()
        ->addAttributeToSelect('name');

    if (!empty($relatedProducts)) {
        foreach ($relatedProducts as $relatedProduct) {
            echo $relatedProduct->getName() . '
'; } } }

In case the products you want to get are related by category, learn how to get product collection by category ID.