Create a custom dynamic tag to show product color swatches in a Listing Builder item

<?php
// Creates a custom dynamic tag {{ my-color-swatches }} to use in the Listing Builder, that displays color swatches for each product.
// This snippet works with swatches from Iconic's WooCommerce Attribute Swatches plugin and colors set as product attribute.
// See: https://facetwp.com/help-center/using-facetwp-with/woocommerce-attribute-swatches/#create-a-custom-dynamic-tag-to-output-color-swatches-for-each-product

add_filter( 'facetwp_builder_dynamic_tag_value', function( $tag_value, $tag_name, $params ) {
    
  // Replace 'my-color-swatches' with the name of your custom dynamic tag name . 
  if ( 'my-color-swatches' == $tag_name ) { 
    
    // Replace 'pa_color' with the name of the WooCommerce attribute used for the product color. 
    // Note that 'pa_' is automatically added by WooCommerce before the attribute's slug.  
    $terms = wp_get_post_terms( $params['post']->ID, 'pa_color', array( 'fields' => 'ids' ) );
    $tag_value = '';
    foreach($terms as $term_id) {
      $color_code = get_term_meta($term_id, 'iconic_was_term_meta', true);
      $color_code = maybe_unserialize($color_code);
      $color_code = $color_code['colour-swatch'];
      if ($color_code) {
        $tag_value .= '<div class="color-swatch" style="background-color: ' . $color_code . '; width: 24px; height:24px; display: inline-block; margin: 0 12px 0 0;"></div>'; // Adapt the CSS as needed.
      }
    }
  }
 
  return $tag_value;
}, 10, 3 );