'How to pre-filter Woocommerce by current category name?

I'm trying pre-filter categories on product archive pages by the current category name using the WP Grid Builder plugin. The idea is to use a single grid to show related products. I have this code here:

function prefix_filter_query( $query_string, $grid_id, $action ) {
    
    // If the content is not filtered on first render.
    if ( 'render' === $action && empty( $query_string ) && 1 === $grid_id ) {
        
        $query_string = [
            'categories' => ['home-decor']
        ];
    } 
    
    return $query_string;
}

add_filter( 'wp_grid_builder/facet/query_string', 'prefix_filter_query', 10, 3 );

It works fine, but I have to create a new grid and hook it for every category. I'd rather have "['home-decor']" be dynamic.

In my head it works like this:

myterm = current_product_category;

$query_string = [
    'categories' => myterm

How can I do this? Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source