Woocommerce Related Products Custom Query Example

Hello developers

In this wordpress woocommerce tips and trics tutorial i will show you woocommerce related products query. If you don't know how to show related products in wordpress from woocommerce then this tutorial is for you.

In this tutorial i will show woocommerce related products from same category. When a user will see a product then we will show some same category products to him. It is a common matter to show related products in ecommerce website.

You can change number of products to show. How to woocommerce change number of related products ?  You can change it from this woocommerce related prodcuts custom query. Let's see the query.

woocommerce-related-products-query

Just use this query and use it in your html tag.

global $post;
$related = get_posts( 
  array( 
  '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 ) {
        setup_postdata($post); 
        $thumbnail = wp_get_attachment_url( get_post_thumbnail_id(get_the_ID()), 'full' );
        $product = wc_get_product( get_the_ID() );
          $permalink = get_the_permalink(get_the_ID());
          $title = get_the_title();
          $price = $product->get_price();
     }
 wp_reset_postdata();
}

 

Check also : How to Pass PHP Data to JavaScript in WordPress

 

Hope it can help you to do your task.

 

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website