→ How to Create Facets from ACF Relationship Fields

UPDATE: FacetWP now includes built-in ACF integration.

Advanced Custom Fields is a popular custom fields plugin for WordPress. It includes basic field types (text, file upload, date), but also includes relationship fields. A relationship field is used to “connect” posts together. They make for neat facets, because you can filter by related posts.

The only issue with ACF relationship fields is the way they’re saved to the database. They’re stored as a serialized string, which makes them a little trickier to interpret. Fortunately, we can tell FacetWP how to properly index relationship fields.

Indexing Relationship Fields

Let’s say you’ve created a new facet named “related_resources”, and you’ve chosen the ACF relationship field from the  Data Source dropdown.

function my_facetwp_index_row( $params, $class ) {
    if ( 'related_resources' == $params['facet_name'] ) {
        $values = (array) $params['facet_value']; // an array of post IDs (it's already unserialized)
        foreach ( $values as $val ) {
            $params['facet_value'] = $val;
            $params['facet_display_value'] = get_the_title( $val );
            $class->insert( $params ); // insert each value to the database
        // skip the default indexing query
        return false;
    return $params;
add_filter( 'facetwp_index_row', 'my_facetwp_index_row', 10, 2 );

The above code says, “If the field name is related_resources, then loop through the array of values and insert each value into the FacetWP index table”.