How to Get Related and Upsell Products in Magento 2?
Learn more on our Blog: https://www.envisionecommerce.com/ho...s-in-magento-2/
Printable View
How to Get Related and Upsell Products in Magento 2?
Learn more on our Blog: https://www.envisionecommerce.com/ho...s-in-magento-2/
app/code/Chapagain/HelloWorld/Block/HelloWorld.php
Printing related, upsell & crosssell product in template (.phtml) fileCode:<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_registry;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\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');
}
}
?>
Here, Object Manager is used to instantiate our custom HelloWorld block class. Then current product information is fetched. After that, current product’s related, upsell and crosssell products are fetched and printed.
Code:
$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('Chapagain\HelloWorld\Block\HelloWorld');
$currentProduct = $myBlock->getCurrentProduct();
if ($currentProduct = $myBlock->getCurrentProduct()) {
$relatedProducts = $currentProduct->getRelatedProducts();
$upSellProducts = $currentProduct->getUpSellProducts();
$crossSellProducts = $currentProduct->getCrossSellProducts();
if (!empty($relatedProducts)) {
echo 'Related Products <br />';
foreach ($relatedProducts as $relatedProduct) {
echo $relatedProduct->getSku() . '<br />';
}
}
if (!empty($upSellProducts)) {
echo 'UpSell Products <br />';
foreach ($upSellProducts as $upSellProduct) {
echo $upSellProduct->getSku() . '<br />';
}
}
if (!empty($crossSellProduct)) {
echo 'CrossSell Products <br />';
foreach ($crossSellProducts as $crossSellProduct) {
echo $crossSellProduct->getSku() . '<br />';
}
}
}
Stage 1: Go to the separate item which you need include upsell item from Catalog > Products, and select items.
Stage 2: On up-sells, strategically pitches and related items segment click on include upsell items.
Stage 3: Select upsell item and snap on include chosen items.
Include upsell in Magento 2: Step 1: Go to the individual item which you need include upsell item from Catalog > Products, and select items. Stage 2: On up-sells, strategically pitches and related items segment click on include upsell items. Stage 3: Select upsell item and snap on include chosen items.