Magento2 | PWA | GraphQL

Display Products sold count and prev next product link on product detail page magento2


In this post we wiil check how to display products sold count and prev next product link with images on product detail page magento2.

Let's start by creating custom module.

You can find complete module on Github at Magelearn_ProductSoldPrevNext




Create folder inside app/code/Magelearn/ProductSoldPrevNext

Add registration.php file in it:

<?php

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magelearn_ProductSoldPrevNext', __DIR__);

Add composer.json file in it:

{
    "name": "magelearn/module-product-sold-prev-next",
    "description": "Display Products sold count and prev next product link on product detail page magento2.",
    "type": "magento2-module",
    "license": "proprietary",
    "version": "1.0.0",
    "authors": [
        {
            "name": "Vijay Rami",
            "email": "vijaymrami@gmail.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\ProductSoldPrevNext\\": ""
        }
    }
}

Add etc/module.xml file in it:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magelearn_ProductSoldPrevNext" setup_version="1.0.0" schema_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

Now first we will modify layout files.
Add app/code/Magelearn/ProductSoldPrevNext/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="product.info.stock.sku">
            <block class="Magento\Catalog\Block\Product\View" name="magelearn_productsoldcount" template="Magelearn_ProductSoldPrevNext::product/product_sold_count.phtml" after="-" cacheable="false"/>
        </referenceContainer>
        
        <referenceContainer name="page.wrapper">
   			<block class="Magelearn\ProductSoldPrevNext\Block\PreviousNext" name="product.info.previousnext" template="Magelearn_ProductSoldPrevNext::product/view/previousnext.phtml" />
		</referenceContainer>
		
		<move element="product.info.previousnext" destination="main.content" before="-"/>
    </body>
</page>

Add app/code/Magelearn/ProductSoldPrevNext/view/frontend/layout/catalog_product_view_type_bundle.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">	
    <body>
	<referenceContainer name="product.info.stock.sku">
        <block class="Magento\Catalog\Block\Product\View" name="magelearn_productsoldcount" template="Magelearn_ProductSoldPrevNext::product/product_sold_count.phtml" after="-" cacheable="false"/>
    </referenceContainer>
        
    <referenceContainer name="page.wrapper">
        <block class="Magelearn\ProductSoldPrevNext\Block\PreviousNext" name="product.info.previousnext" template="Magelearn_ProductSoldPrevNext::product/view/previousnext.phtml" />
    </referenceContainer>
    
    <move element="product.info.previousnext" destination="main.content" before="-"/>
    </body>
</page>

Now as per defined in layout file, we will add our template file at app/code/Magelearn/ProductSoldPrevNext/view/frontend/templates/product/product_sold_count.phtml

<?php $_helper = $this->_helper = $this->helper('Magelearn\ProductSoldPrevNext\Helper\Data'); ?>
<div class="product attribute product_count">
	<strong>Products Sold:</strong>
	<?= $_helper->getSoldQtyByProductId($this->getProduct()->getId()); ?>
</div>

Now we will add our helper file at app/code/Magelearn/ProductSoldPrevNext/Helper/Data.php

<?php

namespace Magelearn\ProductSoldPrevNext\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Reports\Model\ResourceModel\Product\Sold\CollectionFactory;

/**
 * Class Data
 * @package Magelearn\ProductSoldPrevNext\Helper
 */
class Data extends AbstractHelper
{
    /**
     * @var CollectionFactory
     */
    protected $reportCollectionFactory;

    /**
     * Data constructor.
     *
     * @param Context $context
     * @param CollectionFactory $reportCollectionFactory
     */
    public function __construct(
        Context $context,
        CollectionFactory  $reportCollectionFactory
    ) {
        $this->reportCollectionFactory = $reportCollectionFactory;
        parent::__construct($context);
    }

    /**
     * Get the count of Current Products Sold
     *
     * @param null $productId
     * @return int
     */
    public function getSoldQtyByProductId($productId = null)
    {
        $SoldProducts = $this->reportCollectionFactory->create();
        $SoldProductsCount = $SoldProducts->addOrderedQty()->addAttributeToFilter('product_id', $productId);
        if(!$SoldProductsCount->count()) {
            return 0;
        }
        $product = $SoldProductsCount->getFirstItem();
        return (int)$product->getData('ordered_qty');
    }
}

Now to display previous next products data, we will add our block file at app/code/Magelearn/ProductSoldPrevNext/Block/PreviousNext.php

<?php

namespace Magelearn\ProductSoldPrevNext\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\Registry;
use Magento\Framework\ObjectManagerInterface;

class PreviousNext extends Template
{
    protected $_product = null;
    protected $_registry;
    protected $_objectManager;
    protected $_productModel;

	public function __construct(
        Context $context,
        Registry $registry,
        ObjectManagerInterface $objectManager,
        array $data = []
	)
	{
        $this->_registry = $registry;
        $this->_objectManager = $objectManager;
        $this->_productModel = 'Magento\Catalog\Model\Product';
        $this->_categoryModel = 'Magento\Catalog\Model\Category';
        parent::__construct($context,$data);
    }
    
    public function getProduct()
    {
        if (!$this->_product) {
            $this->_product = $this->_registry->registry('product');
        }
        return $this->_product;
    }

    public function getProductModel() {
        return $this->_objectManager->create($this->_productModel);
    }

    public function getCategoryModel() {
        return $this->_objectManager->create($this->_categoryModel);
    }

    public function getCurrentCategory($category_ids)
    {
        $category = $this->getCategoryModel()->load($category_ids[0]);
        return $category;
    }

    public function getCategoryProductIds($category) {
        $category_products = $category->getProductCollection();
        $category_products->addAttributeToSelect('*');
        $category_products->addAttributeToFilter('status',1);
        $category_products->addAttributeToFilter('visibility',4);
        $category_products->addAttributeToSort('position', 'asc');
            
        $cat_prod_ids = $category_products->getAllIds();
        
        return $cat_prod_ids;
    }

    public function getPrevProduct($productId,$category_ids) {
        $category = $this->getCurrentCategory($category_ids);
        $cat_prod_ids = $this->getCategoryProductIds($category);
        $product_id = array_search($productId, $cat_prod_ids);
        $prev_product_id = $product_id - 1;
        $keys = array_keys($cat_prod_ids);

        if(in_array($prev_product_id, $keys)){
            $_prev_prod = $this->getProductModel()->load($cat_prod_ids[$prev_product_id]);
            return $_prev_prod;
        }
        return false;
    }
    
    public function getNextProduct($productId,$category_ids) {
        $category = $this->getCurrentCategory($category_ids);
        $cat_prod_ids = $this->getCategoryProductIds($category);
        $product_id = array_search($productId, $cat_prod_ids);
        $next_product_id = $product_id + 1;
        $keys = array_keys($cat_prod_ids);

        if(in_array($next_product_id, $keys)){
            $_next_prod = $this->getProductModel()->load($cat_prod_ids[$next_product_id]);
            return $_next_prod;
        }
        return false;
    }
}

And template file for previous next products at app/code/Magelearn/ProductSoldPrevNext/view/frontend/templates/product/view/previousnext.phtml

<?php

    $productId = $block->getProduct()->getId();
    $category_ids = $block->getProduct()->getCategoryIds();
    $_previous = $block->getPrevProduct($productId,$category_ids);
    $_next = $block->getNextProduct($productId,$category_ids);
    $category = $block->getCurrentCategory($category_ids);
	
	$_helper = $this->helper('Magento\Catalog\Helper\Output');
    $_imagehelper = $this->helper('Magento\Catalog\Helper\Image');
?>
<div class="magelearn-previous-next">
    <div class="back-categories">
        <p>Back to: <a href="<?= $category->getUrl() ?>" title="<?=$category->getName()?>"><span> <?=$category->getName()?> </span></a></p>
    </div>
    <div class="previous-next-action prev-next-products">
        <?php if($_previous): ?>
        	<?php
		        $productImage = $_imagehelper->init($_previous, 'category_page_grid')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(80);
		        $productImageUrl = $productImage->getUrl();
		    ?>
		    <div class="product-nav product-prev">
	            <a href="<?php print_r($_previous->getProductUrl()); ?>" title="<?php print_r($_previous->getName()); ?>"><span class="icon-open">Previous</span></a>
	            <div class="product-pop theme-border-color">
		            <img class="product-image" src="<?php echo $productImageUrl; ?>" alt="<?php echo $productImage->getLabel(); ?>"/>
		            <h3 class="product-name"><?php echo ucwords(strtolower($_previous->getName())); ?></h3>
		        </div>
	            <?php if($_next): ?><span class="divider">/</span><?php endif; ?>
           </div>
        <?php endif; ?>
        <?php if($_next): ?>
        	<?php
		        $productImage = $_imagehelper->init($_next, 'category_page_grid')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(80);
		        $productImageUrl = $productImage->getUrl();
		    ?>
		    <div class="product-nav product-next">
	            <a href="<?php print_r($_next->getProductUrl()); ?>" title="<?php print_r($_next->getName()); ?>"><span class="icon-open">Next</span></a>
	            <div class="product-pop theme-border-color">
		            <img class="product-image" src="<?php echo $productImageUrl; ?>" alt="<?php echo $productImage->getLabel(); ?>"/>
		            <h3 class="product-name"><?php echo ucwords(strtolower($_next->getName())); ?></h3>
		        </div>
	       </div>
        <?php endif; ?>
    </div>
</div>

We will also add css file at app/code/Magelearn/ProductSoldPrevNext/view/frontend/web/css/source/_module.less to display data properly.

0 Comments On "Display Products sold count and prev next product link on product detail page magento2"

Back To Top