Integrations / Platforms / WordPress / Indexing Other Type of Content
Feb. 18, 2019

Indexing Other Type of Content

Indexing post types

The existing code to index WordPress default posts can be slightly adapted to index any type of posts.

First, we’ll adapt the command to take a new --type option, in order to index other post types. And we use this value where ‘post’ was hard coded:

  • Filter argument for the index name
  • WP_Query argument
  • Name of the filter to convert post to record. We now have post_to_record, page_to_record and so on.
  • Success message

The final method should be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public function reindex_post( $args, $assoc_args ) {
    global $algolia;
    global $table_prefix;

    $type = isset($assoc_args['type']) ? $assoc_args['type'] : 'post';

    $indexName = $table_prefix.$type;
    $index = $algolia->initIndex(
        apply_filters('algolia_index_name', $indexName, $type)
    );
    $index->clearObjects()->wait();


    $paged = 1;
    $count = 0;
    do {
        $posts = new WP_Query([
            'posts_per_page' => 100,
            'paged' => $paged,
            'post_type' => $type,
            'post_status' => 'publish',
        ]);

        if (! $posts->have_posts()) {
            break;
        }

        $records = [];
        foreach ($posts->posts as $post) {
            if ($assoc_args['verbose']) {
                WP_CLI::line('Indexing ['.$post->post_title.']');
            }
            $record = (array) apply_filters($type.'_to_record', $post);

            if (! isset($record['objectID'])) {
                $record['objectID'] = implode('#', [$post->post_type, $post->ID]);
            }

            $records[] = $record;
            $count++;
        }

        $index->saveObjects($records);

        $paged++;

    } while (true);

    WP_CLI::success("$count $type entries indexed in Algolia");
}

Indexing terms

In order to index terms, I’d recommend creating a new command wp algolia reindex_terms and adding a public reindex_terms method below reindex_posts.

Then, you should be able to follow all the previous steps and adapt them to index terms instead of posts.

It’s best to create a different method because Posts and Terms are very different types. They have separate tables in the database, while all posts share the same table, hence the same structure.

Did you find this page helpful?