Skip to content

Instantly share code, notes, and snippets.

@bchiang7
Created March 26, 2020 21:35
Show Gist options
  • Save bchiang7/a12f12e84ce1c11d9d55471037e00f8e to your computer and use it in GitHub Desktop.
Save bchiang7/a12f12e84ce1c11d9d55471037e00f8e to your computer and use it in GitHub Desktop.
<?php
public function reindex($args, $assoc_args) {
// Init global index
$index = $algolia->initIndex('global_search');
// Clear all objects in the index
$index->clearObjects()->wait();
// Get all blog IDs in multisite network
$all_blog_ids = get_sites(array('fields' => 'ids'));
// Get all searchable post types
$searchable_post_types = get_post_types(
array(
'public' => true,
'exclude_from_search' => false
)
);
// Index posts for each site in the multisite network
foreach ($all_blog_ids as $blog_id) {
// Switch to the current blog's context
switch_to_blog($blog_id);
// Loop through searchable post types
foreach ($searchable_post_types as $post_type) {
$paged = 1;
$count = 0;
do {
$posts = new WP_Query([
'posts_per_page' => 100,
'paged' => $paged,
'post_type' => $post_type,
'post_status' => 'publish',
]);
$records = [];
// Loop through each post and serialize them
foreach ($posts->posts as $post) {
// Use post type to get corresponding serializer function
$filter_name = $post->post_type.'_to_record';
// Serialize and split records
$split_records = (array) apply_filters($filter_name, $post);
$records = array_merge($records, $split_records);
$count++;
}
// Save the records in Algolia!
$index->saveObjects($records);
WP_CLI::success("$count $post_type records indexed in Algolia");
$paged++;
} while (true);
}
// Switch back to the current blog's context
restore_current_blog();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment