Magento 2: Reindex One Product Programmatically

Magento 2 reindex one product programmatically of database queries and ensure a smooth shopping experience. However, when a single product is updated, you might not want to reindex the entire catalog. Instead, you can reindex …

Magento 2 reindex one product programmatically of database queries and ensure a smooth shopping experience. However, when a single product is updated, you might not want to reindex the entire catalog. Instead, you can reindex just one product programmatically. This article will guide you through the process of reindexing a single product using a custom script. 

Why Reindex a Single Product?

Reindexing a single product is useful when:

  • A product’s price, stock status, or visibility has changed.
  • You have made programmatic updates and need to reflect changes immediately.
  • Running a full reindex is unnecessary and time-consuming.

Steps to Reindex One Product Programmatically

1. Create a Custom PHP Script

To reindex a single product, create a custom PHP script and place it in your Magento 2 root directory (e.g., reindex_product.php).

2. Use the Following Code

<?php

use Magento\Framework\App\Bootstrap;

use Magento\Framework\ObjectManagerInterface;

use Magento\Framework\Indexer\IndexerRegistry;

require __DIR__ . ‘/app/bootstrap.php’;

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$productId = 123; // Replace with your product ID

$indexerIds = [

    ‘catalog_product_attribute’,

    ‘catalog_product_price’,

    ‘cataloginventory_stock’,

    ‘catalog_product_category’

];

foreach ($indexerIds as $indexerId) {

    try {

        /** @var IndexerRegistry $indexerRegistry */

        $indexerRegistry = $objectManager->get(IndexerRegistry::class);

        $indexer = $indexerRegistry->get($indexerId);

        $indexer->reindexRow($productId);

        echo “Reindexed: $indexerId for product ID $productId \n”;

    } catch (Exception $e) {

        echo “Error: ” . $e->getMessage() . “\n”;

    }

}

3. Run the Script

Execute the script via the command line:

php reindex_product.php

4. Verify the Changes

After running the script, clear the cache to ensure the changes reflect correctly:

php bin/magento cache:flush

Conclusion

Reindexing a single product programmatically in Magento 2 is an efficient way to update product data without reindexing the entire catalog. This approach is particularly useful when dealing with frequent product updates and helps optimize performance. By using the script above, you can easily trigger reindexing for specific products as needed.

Leave a Comment