Upsell products collection in Magento 2 by Product id to display upsell products in Detail Page of the store view.
If you have set right Upsell products based on the main product of the page, That boost your revenue also by customer add the upsell products with the Original products.
Upsell Product list will be displayed on the product detail page by native Magento with simple text, “We found other products you might like!”.
<?php namespace Jesadiya\Upsell\Model; use Psr\Log\LoggerInterface; use Magento\Catalog\Api\ProductRepositoryInterface; class Upsell { /** * @var ProductRepositoryInterface */ protected $productRepository; /** * @var LoggerInterface */ private $logger; public function __construct( ProductRepositoryInterface $productRepository, LoggerInterface $logger ) { $this->logger = $logger; $this->productRepository = $productRepository; } /** * upsell product * * @return array */ public function getUpsellProducts() { $productId = 1; $upsellProduct = []; try { $product = $this->productRepository->getById($productId); $upsell = $product->getUpSellProducts(); if (count($upsell)) { foreach ($upsell as $item) { $upsellProduct[] = $item->getId(); } } } catch (\Exception $exception) { $this->logger->error($exception->getMessage()); } return $upsellProduct; } }
Get all the Upsell products assigned from the admin panel inside the product page, Using the simple code snippet by load product repository way.