How To Get Related Products Collection In Magento 2
E-commerce product page best practices include displaying related products on the product page. It encourages shoppers to purchase those related products and hence increase in the average order value!
Such conversion boosters positively affect the business and hence Magento 2 store owners can implement it using the below code.
Get related products collection in Magento 2 store and allow the shoppers to add the items to the cart easily!
Method to get related products collection in Magento 2:
- Create Extension.php file at app/code/Vendor/Extension/Block folder
1234567891011121314151617181920212223242526272829303132<?phpnamespace 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');}} - Call the below function in your pHTML file
1234567891011$currentProduct = $block->getCurrentProduct();if ($currentProduct = $block->getCurrentProduct()) {$relatedProducts = $currentProduct->getRelatedProducts();if (!empty($relatedProducts)) {foreach ($relatedProducts as $relatedProduct) {echo $relatedProduct->getName().'<br>';}}}
That’s it.
Any doubts about the topic can be mentioned in the Comments section below. I’d be happy to help.
Please share the solution with the Magento community via social media.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
1 Comment
Since the class Magento\Framework\Registry is deprecated what else you can do?
From the class documentation:
* Registry usage as a shared service introduces temporal, hard to detect coupling into system.
* It’s usage should be avoid. Use service classes or data providers instead.
*
* @api
* @deprecated 102.0.0
* @since 100.0.2