Magento – how to get Compared Product collection in magento 2

comparemagento2

How can I get the Products that are already added in the compare list Product Collection. For Visitor and as well as Login Customer. Can anyone guide me to solutions.

Best Answer

public function __construct(
    \Magento\Catalog\CustomerData\CompareProducts $compareProducts
) {
    $this->compareProducts = $compareProducts;
}

/*
    * Get current compare product list
    */
public function getCompareList(){
    return $this->compareProducts->getSectionData();
}

in phtml file,

<?php
    $compareObject = $block->getCompareList();
 ?>
<div class="compare-items">
<?php foreach($compareObject['items'] as $comparelist){                        
 ?>
    <div class="compProd">
        <a class="closeComp" data-href="<?php echo $block->getBaseUrl() ?>ajaxcompare/compare/remove/" data-compare="<?php echo $comparelist['id']; ?>">x</a>
        <span class="gBold cmPrd"><?php echo $comparelist['name']; ?></span>
    </div>
<?php } ?>
</div>
Related Topic