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:
1. Create 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 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>'; } } }
That’s it.
Please share the solution with the Magento community via social media.
Thanks.