How can i get total view count of a product in Magento2?
For any product, you can set the product_id to the report collection
/**
* @param int $id
*
* @return mixed
*/
public function getProductCount($id)
{
/**
* @var \Magento\Catalog\Model\Product\Interceptor $product
*/
//Get Object Manager Instance
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//Load product by product id
$productObj = $objectManager->create('Magento\Catalog\Model\Product')->load($id);
$productcollection = $objectManager->create('\Magento\Reports\Model\ResourceModel\Product\Collection');
$productcollection->setProductAttributeSetId($productObj->getAttributeSetId());
$prodData = $productcollection->addViewsCount()->getData();
if (count($prodData) > 0) {
foreach ($prodData as $product) {
if ($product['entity_id'] == $id) {
return (int) $product['views'];
}
}
}
return 0;
}
And then in your template phtml , use it by
$blockObj= $block->getLayout()->createBlock('Mymodule\Viewcount\Block\Viewcount');
echo $blockObj->getProductCount($_product->getId());
If you want to show product view of current product in product view page then,
i have simple and easy sollution, and you can place it in PHTML file,
/*get current product*/
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
/*get product view*/
$id = $product->getId();
$productObj = $objectManager->create('Magento\Catalog\Model\Product')->load($id);
$productcollection = $objectManager->create('\Magento\Reports\Model\ResourceModel\Product\Collection');
$productcollection->setProductAttributeSetId($productObj->getAttributeSetId());
$prodData = $productcollection->addViewsCount()->getData();
if (count($prodData) > 0) {
foreach ($prodData as $_product) {
if ($_product['entity_id'] == $id) {
echo (int) $_product['views'];
}
}
}
Thank You @leo . work like a magic Thanks
Answer By Sandip Patel Suggested and help From leo.