title: Related Products display first same subcategory
body: <p>Trying to display related products in WooCommerce <strong>first by same subcategory</strong> and when there are no products to show in that, display another products from parent category, avoiding being empty.</p>
  <p>For example:</p>
  <blockquote>
  <p>Fashion &gt; Clothes &gt; T-Shirts</p>
  <p>When there are no t-shirts available to show, display another products from parent category (clothes).</p>
  </blockquote>
  <p>Tried it but it is not working:</p>
  <pre><code>function wc_related_products_by_last_available_depth_term( $related_posts, $product_id, $args ) {
      $product = wc_get_product( $product_id );
      $terms = wp_get_post_terms( $product_id, 'product_cat' );
      $hierarchy = array();
      $cat_id = '';
      // find the depth of terms
      foreach ( $terms as $key =&gt; $term ) {
          $ancestors = get_ancestors( $term-&gt;term_id, 'product_cat' );
          if( $ancestors &amp;&amp; count( $ancestors ) &gt; 1 ) {
              $hierarchy[$term-&gt;term_id] = max($ancestors);
          }elseif( $ancestors ) {
              $hierarchy[$term-&gt;term_id] = $ancestors[0];
          }
          $cat_id = $term-&gt;term_id;
      }
      // if level of depth term available replace $cat_id
      if( $hierarchy ){
         $cat_id = max( array_keys( $hierarchy ) );
      }
  
      $related_posts = get_posts( array(
          'post_type' =&gt; 'product',
          'post_status' =&gt; 'publish',
          'fields' =&gt; 'ids',
          'posts_per_page' =&gt; -1,
          'exclude' =&gt; array( $product_id ),
          'tax_query' =&gt; array(
              array(
                  'taxonomy'     =&gt; 'product_cat',
                  'field'        =&gt; 'id',
                  'terms'        =&gt; array( $cat_id )
              )
          )
      ));
      return $related_posts;
  }
  add_filter( 'woocommerce_related_products', 'wc_related_products_by_last_available_depth_term', 99, 3 ); 
  </code></pre>