Create a custom dynamic tag to output post terms, but exclude top-level parent terms

<?php

// Creates a custom dynamic tag {{ childterms }} to display post terms of a specific taxonomy in a Listing Builder (HTML) item.
// Excludes top-level parent terms, so shows child terms only.
// Displays the term names in a comma-separated list.
// Replace 'my_taxonomy' with the name of your taxonomy.
// Use the custom dynamic tag in a (HTML) builder item like this: {{ childterms }}


add_filter( 'facetwp_builder_dynamic_tag_value', function( $tag_value, $tag_name, $params ) {
  if ( 'childterms' == $tag_name ) {
    $taxonomy = 'my_taxonomy';
    $terms = wp_get_post_terms( $params['post']->ID,  $taxonomy );
    $child_terms = array();

    foreach ( $terms as $term ) {
      $parent_id = $term->parent;
      if ( $parent_id !== 0 ) { // Exclude top-level parent terms (that have a parent ID of 0).
        $child_terms[] = $term->name; // Get term names
      }
    }
    $tag_value = implode( ', ', $child_terms ); // Output the term names as a comma-separated list

  }
  return $tag_value;
}, 10, 3 );