The answer in that topic makes you misunderstand. I've fixed that issue, please do the following steps to limit the number of products in compare products feature:
Step 1: Create registration.php:
File path: app/code/Vendor/Module/registration.php
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_Module', __DIR__);
Step 2: Create module.xml:
File path: app/code/Vendor/Module/etc/module.xml
<?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="Vendor_Module">
<sequence>
<module name="Magento_Catalog"/>
</sequence>
</module>
</config>
Step 3: Create the di.xml file:
File path: app/code/Vendor/Module/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Controller\Product\Compare\Add">
<plugin name="LimitCompareProducts" type="Vendor\Module\Plugin\LimitCompareProducts"/>
</type>
</config>
Step 4: Create LimitCompareProducts.php plugin file:
File path: app/code/Vendor/Module/Plugin/LimitCompareProducts.php
<?php
namespace Vendor\Module\Plugin;
use Magento\Catalog\Controller\Product\Compare\Add;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
use Magento\Catalog\Helper\Product\Compare;
class LimitCompareProducts
{
const LIMIT_TO_COMPARE_PRODUCTS = 2;
/**
* @var ManagerInterface
*/
protected $messageManager;
/**
* @var RedirectFactory
*/
protected $resultRedirectFactory;
/** @var Compare */
protected $helper;
/**
* RestrictCustomerEmail constructor.
* @param Compare $helper
* @param RedirectFactory $redirectFactory
* @param ManagerInterface $messageManager
*/
public function __construct(
RedirectFactory $redirectFactory,
Compare $helper,
ManagerInterface $messageManager
) {
$this->helper = $helper;
$this->resultRedirectFactory = $redirectFactory;
$this->messageManager = $messageManager;
}
public function aroundExecute(
Add $subject,
\Closure $proceed
) {
$count = $this->helper->getItemCount();
if ($count === self::LIMIT_TO_COMPARE_PRODUCTS) {
$this->messageManager->addErrorMessage(
__(
'Compare products cannot contain more than %1 item(s)',
self::LIMIT_TO_COMPARE_PRODUCTS
)
);
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setRefererOrBaseUrl();
}
return $proceed();
}
}
Step 5: Run the setup:upgrade command to make your new module active, and then compile code, deploy static content:
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy -f
Done. This module compatible with all Magento 2 versions(2.0.x...2.3.x...2.4.x...)