WoocommerceWordpressWordpress TricksWp Tricks

Woocommerce related products custom query


Hello to all, welcome to therichpost.com. In this post, I will tell you, Woocommerce related products custom query.

If you are new in WordPress then please have a look on my old posts related to WordPress.

In this post, I am making custom query to show woocommerce related products like, Woocommerce shows in Single product page but In my query, I will show related products for particular user which is logged in, this means logged in user will see only his/her products.

With the wordpress hook, we can add this custom query into Woocommerce single product page, if we want to particular author related products and here is the code and please use this carefully.

global $post;
$related = get_posts( 
  'category__in' => wp_get_post_categories( $post->ID ), 
  'numberposts'  => 4, 
  'post__not_in' => array( $post->ID ),
  'post_type'    => 'product'

if( $related ) { ?>
      foreach( $related as $post ) {
        $url = wp_get_attachment_url( get_post_thumbnail_id(get_the_ID()), 'full' );
        $product = wc_get_product( get_the_ID() );?>
        <li class="post-<?php echo get_the_ID();?> product type-product">
          <a href="<?php echo get_the_permalink(get_the_ID()); ?>">
          <img src="<?php echo $url; ?>">
          <h2><?php echo get_the_title(); ?></h2>
          <span class="price">$ <?php echo $product->get_price(); ?></span>
          <a href="<?php echo get_the_permalink(get_the_ID()); ?>">Buy Now</a>
      /*whatever you want to output*/
    wp_reset_postdata(); ?>
<?php } ?>


If you have any query related to this post then please let me know or comment below.


Thank you

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Positive SSL