I’m trying to display the related products with my custom html output, unfortunately i’m kind of lost on how to do this.

The WP_Query below displays the products that are in stock, what i want is to display all related products of the single product that are in stock with my custom html output, but i can’t find the field and terms to use, if theres any. I’ll be gratefull if anyone knows how to do this.

<?php $args = array(
'post_type' => 'product',
'posts_per_page' => 12,
      'tax_query' => array(
            array(
                'taxonomy' => 'product_visibility',
                'field'    => 'name',
                'terms'         => 'outofstock',
                'operator'      => 'NOT IN',
            ), 
        ),
      );
    $loop = new WP_Query( $args );
    if ( $loop->have_posts() ) {
      while ( $loop->have_posts() ) : $loop->the_post();

      wc_get_template_part("templates/my-custom-product-display");

      endwhile;
    } else {
          echo __( 'No products found' );
        }
          wp_reset_postdata();
    ?>

1 Answer
1

WooCommerce has a built in function that will do this for you called wc_get_related_products().

That will return an array of product IDs which you can then use in a proper custom loop. I recommend you avoid using WP_Query() and get_posts(). See here for an article I wrote on the right way to create a custom WooCommerce loop: https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/

Leave a Reply

Your email address will not be published. Required fields are marked *