Wednesday, May 29, 2024
WoocommerceWordpressWordpress TricksWp Tricks

Woocommerce related products custom query

Woocommerce related products custom query

Hello to all, welcome to 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.

Woocommerce related products custom query
Related products images

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

the authortherichpost
Hello to all. Welcome to Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

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