<?php
// On a taxonomy term page remove terms from facet that are not the same or a sub category of that term
// See the improved example here that fixes depths:
// https://facetwp.com/help-center/developers/hooks/output-hooks/facetwp_facet_render_args/#remove-facet-choices-that-are-not-children-of-the-current-term
add_filter( 'facetwp_facet_render_args', function( $args ) {
if ( 'product_categories' == $args['facet']['name'] && is_tax( 'product_cat' ) ) {
$current_term = get_queried_object_id();
if ( ! empty( $args['values'] ) ) {
foreach ( $args['values'] as $key => $val ) {
$term_id = $val['term_id'];
// this keeps sub-terms of the current term archive page
if ( $val['parent_id'] && in_array( $current_term, get_ancestors( $val['term_id'], 'product_cat', 'taxonomy' ) ) ) {
continue;
// this keeps term for current archive page, delete this else if to if not wanting the current term also
} else if ( $current_term == $val['term_id'] ) {
continue;
// this removes non-matching terms from the choices for the facet.
} else {
unset( $args['values'][$key] );
}
}
$args['values'] = array_values( $args['values'] );
}
}
return $args;
});