FacetWP – limit category facet to the active archive page

<?php

// Only show facet choices specific to the current archive term
function limit_to_archive_term( $where_clause, $facet ) {
    if ( 'urun_kategorileri' == $facet['name'] ) {
        $term_id = (int) FWP()->facet->http_params['term_id'];
        if ( 0 < $term_id ) {
            $taxonomy = FWP()->facet->http_params['taxonomy'];
            $parent = (int) FWP()->facet->http_params['parent'];
            if ( 0 < $parent ) {
                $ancestors = get_ancestors( $term_id, $taxonomy );
                $term_id = array_pop( $ancestors ); // The top-level term is the last array element
            }
            
            $term_ids = (array) get_term_children( $term_id, $taxonomy );
            $term_ids[] = $term_id; // include the parent
            $term_str = implode( ',', $term_ids );
            $where_clause .= " AND f.term_id IN ($term_str)";
        }
    }
    return $where_clause;
}
add_filter( 'facetwp_facet_where', 'limit_to_archive_term', 10, 2 );


// Pass the current archive term (id, taxonomy) to the page
function inject_term_id() {
    $obj = get_queried_object();
?>
<script>
(function($) {
    $(document).on('facetwp-refresh', function() {
        FWP_HTTP.term_id = '<?php echo isset( $obj->term_id ) ? $obj->term_id : ''; ?>';
        FWP_HTTP.taxonomy = '<?php echo isset( $obj->taxonomy ) ? $obj->taxonomy : ''; ?>';
        FWP_HTTP.parent = '<?php echo isset( $obj->parent ) ? $obj->parent : ''; ?>';
    });
})(jQuery);
</script>
<?php
}
add_filter( 'wp_footer', 'inject_term_id', 99 );