Magento Expert Forum - Improve your Magento experience

Results 1 to 2 of 2

How to Get Related and Upsell Products in Magento 2?

  1. #1

  2. #2
    Junior Member
    Join Date
    Dec 2016
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •