I've recently implemented the Algolia Search Wordpress plugin into a new WP build for my client. The site will essentially be used to collect survey data and provide it's admins a robust search functionality.
I've created a custom post type that will contain a unique post for each survey submission. Each survey input field is pushed to a custom field within the post.
In the following example, I'm trying to implement Algolia's custom field push and retrieve featured here: https://community.algolia.com/wordpress/advanced-custom-fields.html#push-custom-fields-to-algolia. My custom post type is entitled 'Submissions' and I'm trying to push a custom field with a key of 'organisation_name' within that post type. Again, I think I have everything set correctly, but this custom field is not being indexed by Algolia. Any help would be greatly appreciated.
// Push custom fields to Algolia
add_filter( 'algolia_post_shared_attributes', 'my_post_attributes', 10, 2 );
add_filter( 'algolia_searchable_post_shared_attributes', 'my_post_attributes', 10, 2 );
/**
* @param array $attributes
* @param WP_Post $post
*
* @return array
*/
function my_post_attributes( array $attributes, WP_Post $post ) {
if ( 'submissions' !== $post->post_type ) {
// We only want to add an attribute for the 'submissions' post type.
// Here the post isn't a 'submission', so we return the attributes unaltered.
return $attributes;
}
// Get the field value with the 'get_field' method and assign it to the attributes array.
// @see https://www.advancedcustomfields.com/resources/get_field/
$attributes['organisation_name'] = get_field( 'organisation_name', $post->ID );
// Always return the value we are filtering.
return $attributes;
}
// Make custom fields searchable
add_filter( 'algolia_posts_index_settings', 'my_posts_index_settings' );
// We could also have used a more general hook 'algolia_posts_index_settings',
// but in that case we would have needed to add a check on the post type
// to ensure we only adjust settings for the 'speaker' post_type.
/**
* @param array $settings
*
* @return array
*/
function my_posts_index_settings( array $settings ) {
if ( 'submissions' !== $post->post_type ) {
return $settings;
}
// Make Algolia search into the 'bio' field when searching for results.
// Using ordered instead of unordered would make words matching in the beginning of the attribute
// make the record score higher.
// @see https://www.algolia.com/doc/api-client/ruby/parameters#attributestoindex
$settings['attributesToIndex'][] = 'unordered(organisation_name)';
// Make Algolia return a pre-computed snippet of 50 chars as part of the result set.
// @see https://www.algolia.com/doc/api-client/ruby/parameters#attributestohighlight
$settings['attributesToSnippet'][] = 'organisation_name:50';
// Always return the value we are filtering.
return $settings;
}