How to add product to compare products using product id programmatically.

Please give me suggestions.


We can use Magento\Catalog\Model\Product\Compare\Item to add compared products. (We should inject this class to the constructor or can use a Dirty Playground)

Take a look the table catalog_compare_item in database. We need to add the customer id to the product compare item. AND, you also need to add the data to report_compared_product_index table - \Magento\Reports\Model\Product\Index\ComparedFactory.

    /** @var $compareItem \Magento\Catalog\Model\Product\Compare\Item */

    /** @var $compareFactory \Magento\Reports\Model\Product\Index\ComparedFactory */

    $productIds = [1,2, 4, 5]; // For example data.
    $customerId = 1; // For example data. Make sure the customer exists.
     foreach ($productIds as $productId) {

        $viewData = [
            'product_id' => $productId,
            'customer_id' => $customerId
  • why this line: $compareItem->unsetData(); exists? Dec 16 '18 at 8:59
  1. Inject the following class in the constructor where you want to use it.


public function __construct(
\Magento\Catalog\Model\Product\Compare\ListCompare $listCompare,
) {
$this->listCompare = $listCompare;

2) use addProducts method of this class to add products to compare list.

$productIds = <your product Ids>;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.