title: WooCommerce - display related products by tags
body: <p>I want to display related products based on tags. I tried several method and none of them worked. Does someone knows is there way to force related products to be displayed based on tags (not on category)</p>
  
  <p>Here is code that I used to do that (I add this piece of code inside functions.php):</p>
  
  <pre><code>//New "Related Products" function for WooCommerce
  function get_related_custom( $id, $limit = 5 ) {
      global $woocommerce;
  
      // Related products are found from category and tag
      $tags_array = array(0);
      $cats_array = array(0);
  
      // Get tags
      $terms = wp_get_post_terms($id, 'product_tag');
      foreach ( $terms as $term ) $tags_array[] = $term-&gt;term_id;
  
      // Get categories (removed by NerdyMind)
  /*
      $terms = wp_get_post_terms($id, 'product_cat');
      foreach ( $terms as $term ) $cats_array[] = $term-&gt;term_id;
  */
  
      // Don't bother if none are set
      if ( sizeof($cats_array)==1 &amp;&amp; sizeof($tags_array)==1 ) return array();
  
      // Meta query
      $meta_query = array();
      $meta_query[] = $woocommerce-&gt;query-&gt;visibility_meta_query();
      $meta_query[] = $woocommerce-&gt;query-&gt;stock_status_meta_query();
  
      // Get the posts
      $related_posts = get_posts( apply_filters('woocommerce_product_related_posts', array(
          'orderby'        =&gt; 'rand',
          'posts_per_page' =&gt; $limit,
          'post_type'      =&gt; 'product',
          'fields'         =&gt; 'ids',
          'meta_query'     =&gt; $meta_query,
          'tax_query'      =&gt; array(
              'relation'      =&gt; 'OR',
              array(
                  'taxonomy'     =&gt; 'product_cat',
                  'field'        =&gt; 'id',
                  'terms'        =&gt; $cats_array
              ),
              array(
                  'taxonomy'     =&gt; 'product_tag',
                  'field'        =&gt; 'id',
                  'terms'        =&gt; $tags_array
              )
          )
      ) ) );
      $related_posts = array_diff( $related_posts, array( $id ));
      return $related_posts;
  }
  add_action('init','get_related_custom');
  </code></pre>