<?php
// A scenario with 2 facets ('locaties' and 'provincie') that both use the same taxonomy 'regio' as data source.
// The provincie facet is set up to index and show only the child terms level of the terms shown in the locaties facet, with the first 'facetwp_index_row' hook snippet
// If a parent term is selected in the locaties facet, the provincie facet will show all child terms in that level, not necessarily direct child terms of the selected parent term in the locaties facet.
// The second snippet makes sure the provincie facet only shows *direct* child terms of the choice selected in the locaties facet.
// Index only the specific depth in the provincie facet.
// Needs re-indexing to work.
add_filter('facetwp_index_row', function($params) {
if ('provincie' == $params['facet_name']) {
// Get the ancestors of the term
$parents = get_ancestors($params['term_id'], 'regio', 'taxonomy');
// Check if the term is exactly two layers deep
if (count($parents) !== 2) {
// If not, set facet_value to an empty string
$params['facet_value'] = '';
}
}
return $params;
});
// Let the provincie facet only show direct child terms of the choice selected in the locaties facet:
add_filter( 'facetwp_facet_html', function( $output, $params ) {
// Check if the facet is 'provincie'
if ('provincie' == $params['facet']['name']) {
// Get the facet values
$values = $params['values'];
// Get the selected value of the 'locaties' facet
$selected_value = FWP()->facet->facets['locaties']['selected_values'][0];
// If the selected value is not null, get the term ID
if (!is_null($selected_value)) {
// Get the term by its slug
$term = get_term_by('slug', $selected_value, 'regio');
// If the term exists, store the term ID in the global variable
if ($term) {
$parent_term_id = $term->term_id;
}
}
// Filter the values based on the parent term
$filtered_values = array_filter($values, function($value) use ($parent_term_id) {
// Check if the value's parent is the specified parent term
return $value['parent_id'] == $parent_term_id;
});
// Generate the new facet HTML
$output = '';
$selected_values = (array) $params['selected_values'];
foreach ($filtered_values as $value) {
$label = esc_html( $value['facet_display_value'] );
$selected = in_array( $value['facet_value'], $selected_values ) ? ' checked' : '';
$selected .= ( '' != $value['counter'] && 0 == $value['counter'] && '' == $selected ) ? ' disabled' : '';
$output .= '<div class="facetwp-checkbox' . $selected . '" data-value="' . esc_attr( $value['facet_value'] ) . '">';
$output .= '<span class="facetwp-display-value">';
$output .= apply_filters( 'facetwp_facet_display_value', $label, [
'selected' => ( '' !== $selected ),
'facet' => $params['facet'],
'row' => $value
]);
$output .= '</span>';
$output .= '<span class="facetwp-counter">(' . $value['counter'] . ')</span>';
$output .= '</div>';
}
}
return $output;
},10,2);