Site icon Hip-Hop Website Design and Development

Get Terms of custom Taxonomy of products with certain Product Category

I have a "Color" custom tax on a Woocommerce site. I want to make a Select to filter by color on Product Categories. If you are on "Sweaters" and there are "red" and "white" they should only appear those two. If you are on "T-shirts" and there are only "red" only red should show up.

I used this: Get terms that are associated with products from current category and got the following code. I got it to work but it returns one term for each product, so I get a list like Red, white, Red, Red, white…

How do I get only: Red, White

    <?php if( $terms = get_terms( array( 'taxonomy' => 'color' ) ) ) :

    if (is_tax('color')){
    $tax_slug = $_GET['product_cat'];
    } else {
    $tax_slug = get_query_var( 'product_cat' );
    }
    
$product_query_args = array(
        'post_type' => 'product',
        'posts_per_page' => -1, 
        'post_status' => 'publish',
        'no_found_rows' => true,
        'update_post_meta_cache' => false, 
        'fields' => 'ids', 
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => $tax_slug,
            )
        ),
    );

$products_request = new WP_Query( $product_query_args );

if ( $products_request->have_posts() ) {
  
  while ( $products_request->have_posts() ) {

    $products_request->the_post();

    // Get ID of currently iterated post
    $id_of_iterated_product = get_the_ID();

    // Retrieve associated brand terms
    $brands = get_the_terms( $id_of_iterated_product, 'color' );

    // Check if there are brand terms associated to iterated post
    if ( ! empty( $brands ) ) {

$cat_var = '?product_cat='.$tax_slug;

      // If so, iterate through them and get the name of each
      foreach( $brands as $brand_key => $brand_object ) {

    $link = get_term_link($brand_object->slug, 'color');
        $url = $link.$cat_var;
       print "<option value='{$url}'>{$brand_object->name}</option>";

      }  }  } } endif; ?>