Last active
March 26, 2020 22:04
-
-
Save bchiang7/fe6b8b1a2deb83a4a136b019659dc2ae 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 | |
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