Posted on

Indexing ACF fields for taxonomy terms

Advanced Custom Fields makes it possible to add custom fields to taxonomy terms.

Creating a category field in ACF
This is how you would create a category field in ACF.

If you set Relevanssi to index custom fields, Relevanssi won’t index these taxonomy custom fields, because taxonomy terms aren’t generally allowed to have custom fields and the default get_post_meta() function in WordPress doesn’t work on taxonomy terms.

Getting the fields indexed requires a bit of custom programming. You need to add a function that reads the contents of the field and adds that to the taxonomy term content. In most basic form, the function looks like this:

add_filter('relevanssi_tax_term_additional_content', 'rlv_term_fields', 10, 2);
function rlv_term_fields($content, $term) {
    $post_id = $term->taxonomy . "_" . $term->term_id;
    $content .= " " . get_field('category_field', $post_id);
    return $content;
}

First you have to generate the post ID for the get_field() function. For taxonomy terms, it’s in the format of taxonomy_termID. Then just use get_field() to get the field content and add it to the content variable the filter provides. With simple text fields, that’s all you need, just repeat the get_field() for all fields you have to include.

With more complicated fields this too gets more complicated, as you have to process the fields and format their contents into a clean string.

Once you add this function and rebuild the index, the taxonomy term fields are included in the index. They are not included in excerpts, though. That requires another function. However, it’s almost the same as our original function, so with small changes, we can use the same function for both purposes:

add_filter('relevanssi_tax_term_additional_content', 'rlv_term_fields', 10, 2);
add_filter('relevanssi_pre_excerpt_content', 'rlv_term_fields', 10, 2);
function rlv_term_fields($content, $term) {
    if (!isset($term->term_id)) return $content;    // not a taxonomy term, skip
    if (isset($term->term_id) && !isset($term->taxonomy)) {
        // this is excerpt-building, where the taxonomy is in $term->post_type
        $term->taxonomy = $term->post_type;
    }
    $post_id = $term->taxonomy . "_" . $term->term_id;
    $content .= get_field('category_field', $post_id);
    return $content;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.