FacetWP – limit subcategories based on parent category

<?php

function fwp_limit_subcategory( $where_clause, $facet ) {
    if ( 'unter_categories' == $facet['name'] ) {

        // See if a category is selected
        foreach ( FWP()->facet->facets as $f ) {
            if ( 'categories' == $f['name'] && ! empty( $f['selected_values'] ) ) {
                $term_slug = $f['selected_values'][0];
                $term = get_term_by( 'slug', $term_slug, 'category' );
                if ( isset( $term->ID ) ) {
                    $where_clause .= " AND f.parent_id = '{$term->ID}'";
                    break;
                }
            }
        }
    }
    return $where_clause;
}
add_filter( 'facetwp_facet_where', 'fwp_limit_subcategory', 10, 2 );