Site icon Hip-Hop Website Design and Development

Woocommerce Related Product by 2 taxonomy

I need to change related product by taxonomy and if taxonomy didnt have enough product, display rest of it from other taxonomy.

I have 2 taxonomy; product_tag and product_cat. Sometimes products in product_tag are not more than 4, so I need to use another taxonomy to fulfill 4 product in related product.

So I need 4 related product, If product_tag has all of them so nothing, if not use product_cat to complete 4 product.

Any help would be greatefull.

<?php
    // get the custom post type's taxonomy terms
    $related_category = wp_get_object_terms( $post->ID, 'product_cat', array('fields' => 'ids') );
    $related_tag = wp_get_object_terms( $post->ID, 'product_tag', array('fields' => 'ids') );
    // arguments
    $args = array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => 4, // you may edit this number
    'orderby' => 'rand',
    'tax_query' => array(
        array(
            'taxonomy' => 'product_tag',
            'field' => 'id',
            'terms' => $related_tag
        )
    ),
    'post__not_in' => array ($post->ID),
    );
    $related_items = new WP_Query( $args );
    // loop over query
    if ($related_items->have_posts()) :
    while ( $related_items->have_posts() ) : $related_items->the_post();
    ?>
    <div class="related_item">
      <div class="Related_image">
        <a href="<?php the_permalink() ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
      </div>
        <div class="Related_title">
          <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><h2>

        </div>
      </div>
    <?php
    endwhile;
    endif;
    // Reset Post Data
    wp_reset_postdata();
    ?>