Override the ListCompare block.
Create Vendor/Module/etc/di.xml on your custom module
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogBlockProductCompareListCompare" type="VendorModuleBlockProductCompareListCompare" />
</config>
Create Vendor/Module/Block/Product/Compare/ListCompare.php
<?php
namespace VendorModuleBlockProductCompare;
class ListCompare extends MagentoCatalogBlockProductCompareListCompare
{
public function __construct(
MagentoCatalogBlockProductContext $context,
MagentoFrameworkUrlEncoderInterface $urlEncoder,
MagentoCatalogModelResourceModelProductCompareItemCollectionFactory $itemCollectionFactory,
MagentoCatalogModelProductVisibility $catalogProductVisibility,
MagentoCustomerModelVisitor $customerVisitor,
MagentoFrameworkAppHttpContext $httpContext,
MagentoCustomerHelperSessionCurrentCustomer $currentCustomer,
MagentoFrameworkObjectManagerInterface $objectManager,
array $data = []
) {
$this->objectManager = $objectManager;
parent::__construct($context,$urlEncoder,$itemCollectionFactory,$catalogProductVisibility,$customerVisitor,$httpContext,$currentCustomer,$data);
}
/**
* Retrieve Product Compare items collection
*
* @return MagentoCatalogModelResourceModelProductCompareItemCollection
*/
public function getItems()
{
if ($this->_items === null) {
$this->_compareProduct->setAllowUsedFlat(false);
$this->_items = $this->_itemCollectionFactory->create();
$this->_items->useProductItem(true)->setStoreId($this->_storeManager->getStore()->getId());
if ($this->httpContext->getValue(MagentoCustomerModelContext::CONTEXT_AUTH)) {
$this->_items->setCustomerId($this->currentCustomer->getCustomerId());
} elseif ($this->_customerId) {
$this->_items->setCustomerId($this->_customerId);
} else {
/****** Custom Code ******/
$sessionManager = $this->objectManager->create('MagentoFrameworkSessionSessionManagerInterface');
$visitor = $sessionManager->getVisitorData();
if(!$this->_customerVisitor->getId() && isset($visitor['visitor_id'])){
$visitorid = $visitor['visitor_id'];
}else{
$visitorid = $this->_customerVisitor->getId();
}
/****** Custom Code ******/
$this->_items->setVisitorId($visitorid);
}
$this->_items->addAttributeToSelect(
$this->_catalogConfig->getProductAttributes()
)->loadComparableAttributes()->addMinimalPrice()->addTaxPercents()->setVisibility(
$this->_catalogProductVisibility->getVisibleInSiteIds()
);
}
return $this->_items;
}
}

