Indexing Other Types of Content
For now, the plugin indexes posts, but you may want to index other types of content from your WordPress instance. To do so, you can leverage post types.
Indexing post types
You can adapt your existing reindex_post
function to index any post type.
First, you want to adapt the command so you can pass it --type
argument. You can use the passed value in the function instead of the hard-coded “post” value. You can also set the index name using your algolia_index_name
filter, and dynamically pick the transform filter based on post type to convert the content into Algolia records.
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
51
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
To index terms, you can add a new public reindex_terms
method in your main Algolia_Command
class to create a wp algolia reindex_terms
command. You can start from the reindex_post
code and adapt it to index terms instead of posts.
Posts and terms have a different structure and live in different tables in your database. The logic might be similar, but it’s recommended to handle them with two separate methods.