Site icon MageComp Blog

How to Reindex Specific Products Programmatically in Magento 2?

How to Reindex Specific Products Programmatically in Magento 2

Hello Magento Friends,

In this blog, I will explain How to Reindex Specific Products Programmatically in Magento 2.

Reindexing specific products in Magento 2 is a useful task when you want to quickly update product information in the search index, category listings, or other areas without reindexing the entire catalog. Reindexing specific products can help improve the performance and accuracy of your Magento 2 store.

Let’s check out the process for reindexing specific products programmatically in Magento 2.

Steps to Reindex Specific Products Programmatically in Magento 2:

Step 1: Create a custom PHP script like reindex_products.php

<?php
use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
try {
	$productSkus = ['YOUR_SKU_1', 'YOUR_SKU_2'];
	$indexerFactory = $objectManager->get(\Magento\Indexer\Model\IndexerFactory::class);
	$indexerIds = ['catalog_product_attribute', 'cataloginventory_stock'];

	foreach ($productSkus as $productSku) {
	    foreach ($indexerIds as $indexerId) {
		$indexer = $indexerFactory->create();
		$indexer->load($indexerId);
		$indexer->reindexRow($productSku);
	    }
	    echo "Reindexed product with SKU: $productSku\n";
	}
}
catch (\Exception $e){
    echo "****** Exception Throw ************* \n";
    echo $e->getMessage() . " \n";
}
?>

Reindex the Specific Product(s).

You can get loop through the product SKU(s) and trigger the reindexing process for each product.

Step 2: Execute the Script

Save the script and execute it via the command line using PHP:

php reindex_products.php

Here is the Screenshot:

Conclusion:

That’s it! You’ve successfully reindexed specific products in Magento 2. This process can help you keep your product data accurate and up-to-date without the need for a full reindex, which can be time-consuming on large catalogs.

To perform reindexing of the whole store check the below articles,

In case you find difficulty in performing reindexing  of specific products in Magento 2, you can share with me through the comment section and I will be quick to respond to you with the solution.

Happy Coding!

Exit mobile version