app/code/Chapagain/HelloWorld/Block/HelloWorld.php
Code:
<?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');
}
}
?>
Printing related, upsell & crosssell product in template (.phtml) file
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 />';
}
}
}
Bookmarks