How to Set limit to Compare product in Magento 2?

How to Set limit to Compare product in Magento 2?

As we know that in magento 2 we can add as many product to compare, but in this case we can set limit and add only 4 products in compare section so that it would be easy to compare and check two products.

Step 1 : Create a module named as app/code/Company/Catalog

Step 2 : Create Registration.php

Step 3 : Create a file inside following folder structure :-
app/code/Company/Catalog/Model/Plugin/Compare/LimitToCompareProducts.php

Step 4 : Create a file inside following folder structure :- app/code/Company/Catalog/etc/frontend/di.xml

Step 5: Create a file inside following folder structure :-
app/code/Company/Catalog/etc/module.xml

# Add the following code in app/code/Company/Catalog/etc/frontend/di.xml
# Add the following code in app/code/Company/Catalog/Model/Plugin/Compare/LimitToCompareProducts.php

$this->resultRedirectFactory = $redirectFactory;
$this->messageManager = $messageManager;
}

public function aroundExecute(
\Magento\Catalog\Controller\Product\Compare\Add $subject,
\Closure $proceed
){

$count = $this->helper->getItemCount();
if($count > self::LIMIT_TO_COMPARE_PRODUCTS) {
$this->messageManager->addErrorMessage(
‘You can add the compared products under 3 item(s)’
);

/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setRefererOrBaseUrl();
}

return $proceed();
}
}

For Customized Business Solutions at best prices Contact Us now