<?php
/** Indexes all values of an ACF 'endorsement' Checkbox field (set to output an array of 'value : label' choices),
** for posts of post type 'csg_brand' that have a company ID field set.
** See: https://facetwp.com/help-center/developers/hooks/indexing-hooks/facetwp_index_row/
*/
add_filter( 'facetwp_index_row', function( $params, $class ) {
// The 'refine_by' facet is set up with 'Post Type' as data source. 'csg_brand' is a post type.
if ( 'refine_by' == $params['facet_name'] && 'csg_brand' == $params['facet_value'] ) {
$post_id = $params['post_id'];
// Get the company ID from the current 'csg_brand' post
$company_id = get_post_meta( $post_id, 'company', true );
$company_id = $company_id[0];
if ( isset( $company_id ) && $company_id > 0 ) {
$field = get_field_object( 'endorsements', $company_id );
$checkboxes_values = $field['value'];
foreach ( $checkboxes_values as $checkbox_value ) {
if ( is_array( $checkbox_value ) ) {
$facet_value = FWP()->helper->safe_value( $checkbox_value['value'] );
$facet_display_value = $checkbox_value['label'];
} else {
$facet_value = FWP()->helper->safe_value( $checkbox_value );
$facet_display_value = $checkbox_value;
}
$params['facet_value'] = $facet_value;
$params['facet_display_value'] = $facet_display_value;
$class->insert( $params );
}
$params['facet_value'] = ''; // skip the original row
} else {
// No valid company ID found, set facet_value to empty to avoid indexing
$params['facet_value'] = ''; // skip indexing
}
}
return $params;
}, 10, 2 );