How to Get Related and Upsell Products in Magento 2?

  • Posted by Envision Ecommerce
  • /
  • December 3, 2016
how-to-get-related-and-upsell-products-1

In our recent “How to Magento 2” post, we have explained about how to get customer data from an ID in Magento 2. Today, we will see how to get Related and Upsell products in Magento 2. Before diving into the “How to” section, there are a few basic things you need to know about Upsell & Related products.

Here is a super brief and basic explanation of Upsell & Related Products:

Upsell products are the product suggestions displayed to customers based on the features of a product they are currently viewing. These product suggestions may have more price but offer better quality and features. These Upsell product suggestions are meant to change the mood of a customer to spend a little more to buy a more featured product.

However, related products include those product recommendations that intend to make customer purchase more products including the one he is currently viewing.

Now you may be ready to get Related and Upsell products in Magento 2. You can follow the steps as mentioned below to call Related and Upsell products:

Step 1: First of all, add the php file in the block directory of your custom module.

app/code/Envision/Eecom/Block/MyProducts.php

Step 2: To fetch or to call Related and Upsell products in your .phtml file, use the following code:

$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('Envision\Eecom\Block\MyProducts');
 
$existingProduct = $myBlock->getCurrentProduct();
 
if ($existingProduct = $myBlock->getCurrentProduct()) {
    $relatedProducts = $existingProduct->getRelatedProducts();
    $upSellProducts = $existingProduct->getUpSellProducts();
        
    if (!empty($relatedProducts)) {
        echo 'Related Products 
';    
        foreach ($relatedProducts as $relatedProduct) {
            echo $relatedProduct->getSku() . '
';        
        }
    }    
    
    if (!empty($upSellProducts)) {
        echo 'UpSell Products 
';
        foreach ($upSellProducts as $upSellProduct) {
            echo $upSellProduct->getSku() . '
';        
        }
    }
    
}

That is all. Pretty easy and simple, isn’t it? If you are still unsure about this “How to Magento 2” method or need further help in getting Related and Upsell products in Magento 2, you can contact our professional Magento Support.