WebDevStudios / wp-search-with-algolia

Improve search on your site. Autocomplete is included, along with full control over look, feel and relevance.

Home Page:https://wordpress.org/plugins/wp-search-with-algolia/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add ACF Custom Field as attribute to taxonomy

vibrains opened this issue · comments

I have a taxonomy index which is currently only registering basic attributes:

  • objectID
  • name
  • description
  • posts_count
  • term_id
  • taxonomy
  • slug
  • permalink

I would like to also add an ACF field as an attribute.

Which hook should I be using in order to do this?
https://github.com/WebDevStudios/wp-search-with-algolia/wiki/Filter-Hooks

Hi @vibrains

You would want to use either the algolia_term_record filter if you want the filter running on every term regardless of taxonomy, or the algolia_term_{$taxonomy}_record filter where the {$taxonomy} portion is the taxonomy slug. For example algolia_term_post_tag_record for standard tags.

With both filters, you'll get an array of data, with the array key representing the property, and the array value representing the value. You'll also get the current WP_Term object that's being indexed as the 2nd parameter, so that you can look things up in regard to the term. For example, fetching the ACF data based on the $item->term_id. Just return the newly amended array back to the filter, and the data should show up in Algolia, ready to be used.

Quick dummy example. I know it doesn't use ACF, but same principles will apply for you.

function wpswa_example_term_edit( $record, $item ) {
    $featured_img = get_term_meta( $item->term_id, 'featured_img', true );

    // Setting one by default so that you don't have to worry about the property not
    // existing, when it comes to templating time.
    $record['featured_img'] = '';

    if ( ! empty( $featured_img ) ) {
        // In your indexed object in Algolia.com, you should see a "featured_img"
        // property for each term that had a featured image set.
        $record['featured_img'] = $featured_img;
    }

    return $record;
}
add_filter( 'algolia_term_post_tag_record', 'wpswa_example_term_edit', 10, 2 )

You can see the whole spot where we construct the defaults in your message above, at:
https://github.com/WebDevStudios/wp-search-with-algolia/blob/main/includes/indices/class-algolia-terms-index.php#L91-L110

Closing the issue as a support question only, but feel free to comment on it as needed.