How to display up-sell products in checkout page magento 2 ?

Today will show you how to show upsell products in checkout page magento 2 .

Best Magento 2 Upsell Extensions

in module of you create a file system.xml to config extension displayUpsell.

app/code/Magepow/DisplayUpsell/etc/adminhtml/system.xml:

Then put the following content into it:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="magepow" translate="label" sortOrder="1">
<label>Magepow</label>
</tab>
<section id="magepow_displayupsell" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<class>separator-top</class>
<label>Display Upsell</label>
<tab>magepow</tab>
<resource>Magepow_DisplayUpsell::display_upsell</resource>
<group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
<label>General Settings</label>
<field id="enabled" translate="label comment" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
<label>Enabled</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="limit" translate="label comment" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
<label>Max Items</label>
<comment><![CDATA[Number of products you want to display.]]></comment>
</field>
</group>
</section>
</system>
</config>

Next create a file app/code/Magepow/DisplayUpsell/etcconfig.xml

Then put the following content into it:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<magepow_displayupsell>
<general>
<enabled>1</enabled>
<limit>10</limit>
</general>
</magepow_displayupsell>
</default>
</config>

Next create a Helper:

app/code/Magepow/DisplayUpsell/Helper/Data.php

Then put the following content into it:

<?php

namespace Magepow\DisplayUpsell\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var array
*/
protected $configModule;

public function __construct(
\Magento\Framework\App\Helper\Context $context
)
{
parent::__construct($context);
$this->configModule = $this->getConfig(strtolower($this->_getModuleName()));
}

public function getConfig($cfg='')
{
if($cfg) return $this->scopeConfig->getValue( $cfg, \Magento\Store\Model\ScopeInterface::SCOPE_STORE );
return $this->scopeConfig;
}

public function getConfigModule($cfg='', $value=null)
{
$values = $this->configModule;
if( !$cfg ) return $values;
$config = explode('/', $cfg);
$end = count($config) - 1;
foreach ($config as $key => $vl) {
if( isset($values[$vl]) ){
if( $key == $end ) {
$value = $values[$vl];
}else {
$values = $values[$vl];
}
}

}
return $value;
}
}

Next create Block:

app/Magepow/DisplayUpsell/Block/Checkout/ProductUpsell.php

Then put the following content into it:

<?php
namespace Magepow\DisplayUpsell\Block\Checkout;
use Magento\Framework\View\Element\Template;
use Psr\Log\LoggerInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\Context as ContextProduct;

class ProductUpsell extends Template{
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
protected $_cart;
protected $imageBuilder;
/**
* @var LoggerInterface
*/
private $logger;

public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
ContextProduct $contextProduct,
ProductRepositoryInterface $productRepository,
\Magento\Checkout\Model\Cart $cart,
LoggerInterface $logger,
array $data = []
) {

$this->logger = $logger;
$this->productRepository = $productRepository;
$this->_cart = $cart;
$this->imageBuilder = $contextProduct->getImageBuilder();
parent::__construct($context, $data);
}
public function getProductData()
{
$items = [];
$productInfo = $this->_cart->getQuote()->getItemsCollection();
foreach ($productInfo as $item){
$items[] = $item->getProductId();
}

return $items;
}
/**
* upsell product
*
* @return array
*/
public function getUpsellProducts()
{
$upsellProduct = array();
$productIds = $this->getProductData();
foreach ($productIds as $productId) {
$product = $this->productRepository->getById($productId);
$upsell = $product->getUpSellProducts();
if (count($upsell)) {
foreach ($upsell as $item) {
$upsellProduct[] = $item->getId();
}
}
}
return $upsellProduct;
}
/**
* Retrieve product image
*
* @param \Magento\Catalog\Model\Product $product
* @param string $imageId
* @param array $attributes
* @return \Magento\Catalog\Block\Product\Image
*/
public function getImage($product, $imageId, $attributes = [])
{
return $this->imageBuilder->create($product, $imageId, $attributes);
}
/**
* getProductPrice ]
* @param \Magento\Catalog\Model\Product $product
* @return productPrice
*/
public function getProductPrice(\Magento\Catalog\Model\Product $product)
{
return $this->getProductPriceHtml(
$product,
\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
\Magento\Framework\Pricing\Render::ZONE_ITEM_LIST
);
}
/**
* [getProductPriceHtml description]
* @param \Magento\Catalog\Model\Product $product
* @param $priceType
* @param $renderZone
* @param array $arguments
* @return $price
*/
public function getProductPriceHtml(
\Magento\Catalog\Model\Product $product,
$priceType,
$renderZone = \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST,
array $arguments = []
) {
if (!isset($arguments['zone'])) {
$arguments['zone'] = $renderZone;
}

/** @var \Magento\Framework\Pricing\Render $priceRender */
$priceRender = $this->getLayout()->getBlock('product.price.render.default');
$price = '';

if ($priceRender) {
$price = $priceRender->render($priceType, $product, $arguments);
}
return $price;
}
}

Next, create a layout here, I want to show the extra sale on the checkout page so I will overwrite the file checkout_index_index.xml:

app/code/Magepow/DisplayUpsell/view/layout/checkout_index_index.xml

Then put the following content into it:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="checkout" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Magepow\DisplayUpsell\Block\Checkout\ProductUpsell" name="content.upsell" template="Magepow_DisplayUpsell::productupsell.phtml" before="checkout.root" cacheable="false"/>
</referenceContainer>
</body>
</page>

Next, create a productupsell.phtml:

app/code/Magepow/DisplayUpsell/view/templates/productupsell.phtml

Then put the following content into it:

<?php
$test = $this->getMediaUrl();
$helper = $this->helper('Magepow\DisplayUpsell\Helper\Data');
$isEnabled = $helper->getConfigModule('general/enabled');
if( !$isEnabled ) return;
$limit = $helper->getConfigModule('general/limit');
$upsellProductItem = $this->getUpsellProducts();
$upsellProductItems = array_unique($upsellProductItem);
$upSellProducts = array_slice($upsellProductItems,0,$limit);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$image = 'new_products_content_widget_grid';

?>
<?php if($upSellProducts && count($upSellProducts) > 0) : ?>
<div id="cms-static-upsell-products" class="cms-static-upsell-products upsell-products">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="upsell-content">
<div class="block-title title">
<strong id="block-upsell-heading" class="block-upsell" role="heading" aria-level="2">Upsell Products</strong>
</div>
<div class="productUpsell products wrapper grid products-grid" data-infinite="true" data-autoplay="true" data-autoplay-speed="2000" data-dots="true" data-speed="300" data-slides-To-Show="4",data-slides-To-Scroll="1",data-space="15" data-responsive= '[{"breakpoint": "1024", "settings": {"slidesToShow": "4"}}, {"breakpoint": "800", "settings": {"slidesToShow": "3"}}, {"breakpoint": "600", "settings": {"slidesToShow": "2"}}, {"breakpoint": "460", "settings": {"slidesToShow": "1"}}]'>
<?php foreach ($upSellProducts as $upSellProduct) : ?>
<?php $product = $objectManager->create('Magento\Catalog\Model\Product')->load($upSellProduct); ?>
<ol class="item product product-item" >
<div class="product-item-info ">
<div class="images-container">
<div class="product name product-item-link" href="<?php echo $product->getProductUrl();?>">
<h2 class="product-name">
<a class="product-item-link" title="<?php echo $product->getName();?>" href="<?php echo $product->getProductUrl();?>"><?php echo $product->getName();?></a>
</h2>
</div>
<div class="product-hover">
<a href="<?php echo $product->getProductUrl();?>" class="product photo product-item-photo">

<span class="product-image-container">
<span class="product-image-wrapper">
<?= $block->getImage($product,$image)->toHtml() ?>
</span>
</a>
</div>
<div class="hover-box">
<div class="product actions">
<div class="price-box price-final_price">
<span class="price-container price-final_price" >
<span class="price-wrapper ">
<span class="price">
<?= $block->getProductPrice($product) ?>
</span>
</span>
</span>
</div>
<div class="actions-primary">
<?php if ($product->isSaleable()): ?>
<?php if ($product->getTypeInstance()->hasRequiredOptions($product)): ?>
<?php echo $block->getBlockHtml('formkey')?>
<button class="action tocart primary button btn-cart" data-mage-init='{"redirectUrl": {"url": "<?php echo $block->getAddToCartUrl($product) ?>"}}' type="button" title="<?php echo __('Add to Cart') ?>">
<i class="icon icon-add-to-cart"></i>
<span><?php echo __('Add to Cart') ?>
</span>
</button>
<?php else: ?>
<form data-role="tocart-form" action="<?php echo $objectManager->get('\Magento\Catalog\Block\Product\ListProduct')->getAddToCartUrl($product);; ?>" method="post">
<div class="btn">
<?php echo $block->getBlockHtml('formkey')?>
<button type="submit" title="Add to Cart" class="action tocart primary button btn-cart" type="submit" title="<?php echo __('Add to Cart') ?>">
<i class="icon icon-add-to-cart"></i>
<span>Add to Cart</span>
</button>
</div>
</form>
<?php endif; ?>
<?php endif; ?>
<div class="add-to-links actions-secondary" data-role="add-to-links">
<a href="#" class="action tocompare"
data-post='<?php echo $this->helper('Magento\Catalog\Helper\Product\Compare')->getPostDataParams($product);?>'
data-role="add-to-links"
title="<?php echo __('Add to Compare'); ?>">
<i class="icon icon-compare"></i><?php echo __('Compare') ?>
</a>
<a href="#" data-post='<?php echo $this->helper('Magento\Wishlist\Helper\Data')->getAddParams($product) ?>' class="action towishlist" data-action="add-to-wishlist" title="<?php echo __('Add to Wishlist') ?>">
<i class="icon icon-favorites"></i><?php echo __('Wishlist') ?>
</a>

</div>
</div>
</div>
</div>
</div>
</div>
</ol>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
</div>
</div>
<?php endif ?>
<script type="text/x-magento-init">
{
"[data-role=tocart-form], .form.map.checkout": {
"catalogAddToCart": {}
}
}
</script>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"wishlist": {
"component": "Magento_Wishlist/js/view/wishlist"
}
}
}
}
}
</script>
<script type="text/javascript">
require([ 'jquery', 'magiccart/slick', 'alothemes', ], function($, slick, alothemes){
var productUpsell = $('.upsell-content .productUpsell');
if(productUpsell.length) $('head').append(magicproduct(productUpsell, '.item')); });
</script>

Run the “setup:upgrade” command

Running this command makes your new module active, notifying Magento of its presence.

php bin/magento setup:upgrade

next running this command deploy:

php bin/magento setup:static-content:deploy -f

Next running this command delete cache:

php bin/magento cache:flsuh

hope this article will help you in some way, You can see useful articles in the next articles.