How to get related product by category

<?php
/**
* Related Products
*

*/

if ( ! defined( ‘ABSPATH’ ) ) {
exit;
}

global $post, $product, $woocommerce_loop;

if ( is_singular(‘product’) ) {
$terms = wp_get_post_terms( $post->ID, ‘product_cat’ );

foreach ( $terms as $term ) $cats_array[] = $term->term_id;
$query_args = array( ‘orderby’ => ‘rand’, ‘post__not_in’ => array( $post->ID ), ‘posts_per_page’ => 4, ‘no_found_rows’ => 1, ‘post_status’ => ‘publish’, ‘post_type’ => ‘product’, ‘tax_query’ => array(
array(
‘taxonomy’ => ‘product_cat’,
‘field’ => ‘id’,
‘terms’ => $cats_array
)));
$r = new WP_Query($query_args);
if ( $r->have_posts() ) : ?>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s