How To Do Reindexing Programmatically In Magento 2
Posted by: Crawlbytes Comments: 0

How To Do Reindexing Programmatically In Magento 2

Reindexing is a critical function in any eCommerce platform as it ensures that the website’s data is up-to-date and accurate. In Magento 2, reindexing can be done manually or automatically, but in some cases, you may need to reindex programmatically. In this article, we will discuss how to do reindexing programmatically in Magento 2.

Prerequisites:

Before we dive into the process of reindexing programmatically in Magento 2, you need to ensure that you have the following:

  • Basic knowledge of Magento 2 structure and coding
  • Access to the Magento 2 codebase
  • SSH access to the server
  • A text editor

Step 1: Create a new file

The first step in reindexing programmatically in Magento 2 is to create a new file. Open your text editor and create a new PHP file in the root directory of your Magento 2 installation. You can name the file whatever you want, but for the sake of this article, let’s name it “reindex.php”.

Step 2: Add the code to the file

Now that you have created the file, it’s time to add the code that will reindex your Magento 2 data. Copy and paste the following code into your “reindex.php” file:

PHP Code:


<?php
use \Magento\Framework\App\Bootstrap;
require __DIR__ . ‘/app/bootstrap.php’;
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get(‘Magento\Framework\App\State’);
$state->setAreaCode(‘frontend’);
$indexer = $obj->get(‘Magento\Indexer\Model\Indexer\CollectionFactory’)->create()->getItems();
foreach ($indexer as $index) {
$index->reindexAll();
}


Step 3: Save the file

After adding the code to the file, save the file in the root directory of your Magento 2 installation.

Step 4: Run the file

The last step in reindexing programmatically in Magento 2 is to run the file you just created. To do this, log in to your server via SSH and navigate to the root directory of your Magento 2 installation. Then, run the following command:

  • php reindex.php

This command will execute the “reindex.php” file, and Magento 2 will start reindexing your data.

Conclusion:

In conclusion, reindexing is an essential function that ensures the accuracy and up-to-dateness of your Magento 2 data. While reindexing can be done manually or automatically, sometimes you may need to reindex programmatically. By following the steps outlined in this article, you can reindex your Magento 2 data programmatically quickly, and easily. Crawlbytes is looking your feedback:

Share this post