Skip to content

Instantly share code, notes, and snippets.

@bchiang7
Last active March 26, 2020 22:04
Show Gist options
  • Save bchiang7/fe6b8b1a2deb83a4a136b019659dc2ae to your computer and use it in GitHub Desktop.
Save bchiang7/fe6b8b1a2deb83a4a136b019659dc2ae to your computer and use it in GitHub Desktop.
<?php
add_action('save_post', 'algolia_save_post', 10, 3);
function algolia_save_post($id, $post, $update) {
global $algolia;
$post_type = $post->post_type;
$post_status = $post->post_status;
$searchable_post_types = get_post_types(
array(
'public' => true,
'exclude_from_search' => false
)
);
if (in_array($post_type, $searchable_post_types)) {
// Only reindex posts that have been published or trashed
$is_invalid_status = $post_status != 'publish' && $post_status != 'trash';
if (wp_is_post_revision($id) || wp_is_post_autosave($id) || $is_invalid_status) {
return $post;
}
// Serialize post
$filter_name = $post_type.'_to_record';
$records = (array) apply_filters($filter_name, $post);
// Get global index
$canonical_index_name = apply_filters('get_algolia_index_name', 'global_search');
$global_index = $algolia->initIndex($canonical_index_name);
// Delete all records using the distinct_key attribute
$filter_to_delete = 'distinct_key:'.$records[0]['distinct_key'];
// Make sure to delete split records if they exist
$global_index->deleteBy(['filters' => $filter_to_delete]);
if ($post_status == 'publish') {
$global_index->saveObjects($records);
}
}
return $post;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment