Sorry for my typo: …” but I canNOT figure out how to correctly format ACF fields like”
For other people looking for this information, here’s an example of how to add a custom taxonomy to the collection, show it as a facet and show it in your search results:
Formatting the data coming from the custom taxonomy (add this to the cm_typesense_format_sources_data
funtion):
//Format custom taxonomy
$customTaxonomyTerms = get_the_terms($object_id, 'custom_taxonomy');
$customTaxonomy = [];
foreach ($customTaxonomyTerms as $customTaxonomyTerm) {
$customTaxonomy[] = $customTaxonomyTerm->name;
}
$formatted_data['custom_taxonomy_name'] = $customTaxonomy;
Adding your custom post type to the custom schema and showing it as a facet
...
['name' => 'custom_taxonomy_name', 'type' => 'string[]', 'facet' => true],
...
Displaying the custom taxonomy in your custom search results template:
<div class="hit-key-custom-taxonomy"><em>Custom taxonomy:</em>
data.custom_taxonomy_name
</div>
That’s it!
And another example of formatting a simple ACF textarea and adding it to the schema.
//Format ACF textarea field called 'textarea' inside a ACF group field called 'example_group_field'
$textarea = get_field('example_group_field
_textarea', $object_id);
$formatted_data['textarea_name'] = wp_strip_all_tags($textarea);
...
['name' => 'textarea_name', 'type' => 'string'],
...
Plugin Contributor
Sachyya
(@sachyya-sachet)
Hello @studiobovenkamer , glad that you figured it out. Thank you for your feedback and solution.
Regarding adding only the ACF fields to the schema and adding data to it. Add the following code to your child-theme:
// Adding the ACF field to schema to be indexed
function cm_typesense_add_book_schema( $schema, $name ) {
if ( $name == 'post' ) {
$schema['fields'][] = [ 'name' => 'acf_textarea', 'type' => 'string' ];
}
return $schema;
}
add_filter( 'cm_typesense_schema', 'cm_typesense_add_book_schema', 10, 2 );
// Format the data to be sent to above added ACF field in schema
function cm_typesense_format_book_data ( $formatted_data, $raw_data, $object_id, $schema_name ) {
if ( $schema_name == 'post' ) {
$acf_textarea_value = get_field( 'text_area', $object_id );
$formatted_data['acf_textarea'] = $acf_textarea_value;
}
return $formatted_data;
}
add_filter( 'cm_typesense_data_before_entry', 'cm_typesense_format_book_data', 10, 4 );
Please make sure to Delete and Re-index your post type after making this change.
Hope this helps.
Regards,
Sachet