How do I make my terms for each product display via foreach loop? (woocommerce)

The problem is here:

                while ( $query->have_posts() ) {
                    $query->the_post();
                    function filter_categories($categories) {
                            foreach ($categories as $category) {
                                echo $category->name;
                            }
                    }

You shouldn’t declare a function inside a loop. Every time it loops around the filter_categories function gets declared again, but named functions can only be declared once, so it crashes the second time round, and everything stops.

If you look in your PHP error log, you should see an error message about redeclaring filter_categories confirming this.