How to Programmatically Index Posts using ElasticPress

ElasticPress uses WordPress actions and filters to keep your content automatically synced: every time a post, page, or custom post type is added, edited, or deleted via WordPress functions, ElasticPress will sync that content in your Elasticsearch index.

There are some cases where that does not happen though: if you change things directly into the database or add content through a process that sets the WP_IMPORTING constant as true. For cases like these, you can sync your content programmatically in some different ways:

Index a single content

If you need to sync just a few pieces of content, you can sync them one by one, using the index method of the related Indexable object:

PHP
\ElasticPress\Indexables::factory()->get( 'post' )->index( $post_id, true );

Index content in batches

When dealing with a bigger number of posts, it is better to send them in batches to Elasticsearch, saving some time by sending fewer requests. To do that, you can use ElasticPress builtin queue.

First, you need to add posts to the queue, and then sync all posts in that queue:

PHP
// The SyncManager object related to the indexable being used
$sync_manager = \ElasticPress\Indexables::factory()->get( 'post' )->sync_manager;

// Add posts to the queue
$sync_manager->add_to_queue( $post_id );
...

// Sync the whole queue
$sync_manager->index_sync_queue();

Using the full_index() method

If you want to fully mimic ElasticPress’ sync process, you can use the full_index method of the IndexHelper class.

PHP
\ElasticPress\IndexHelper::factory()->full_index( $args );

For the full list of arguments, check the class source code. If you need some inspiration, check how we call the method in our WP-CLI command. Lastly, if you want to understand the sync process in depth, check our Sync Process article.