<?php
global $product;
$up_sell_ids = $product->get_upsell_ids();
$prod_cats = get_the_terms($post->ID, 'product_cat');
foreach ($prod_cats as $term) {
  if ($term->parent === $prod_cats[0]->term_id) {
    $subcat[] = $term->term_id;
  }
}
if(empty($subcat)) {
  foreach ($prod_cats as $term) {
      $subcat[] = $term->term_id;
  }
}

$prod_args = array(
  'post_type' => 'product',
  'posts_per_page'  => 4,
  'orderby'        => 'rand',
  'post__not_in'   => array($product->id),
  'tax_query' => array(
    array(
      'taxonomy' => 'product_cat',
      'field'    => 'id',
      'terms'    => $subcat,
    ),
  ),
  'meta_query' => [
    [
        'key' => '_stock',
        'value' => 0,
        'compare' => '>',
        'type' => 'NUMERIC'
    ]
  ],
);
$prod_posts = new WP_Query($prod_args);
if ($prod_posts->have_posts()) :
  echo '<div class="related-products">'; ?>
  <h3 class="related-title"><?php _e('Prodotti simili', 'blanka'); ?></h3>
  <div class="related-prod-slider row">
    <?php while ($prod_posts->have_posts()) : $prod_posts->the_post();
      echo '<div class="prod-wrapper col-1-2 col-md-1-4">';
      get_template_part('inc/teaser/_teaser', 'product');
      echo '</div>';
    endwhile; ?>
  </div><!-- slider -->
<?php echo '</div><!--related-->';
endif;
wp_reset_query(); ?>