Created
March 26, 2020 21:35
-
-
Save bchiang7/a12f12e84ce1c11d9d55471037e00f8e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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