public static function getRelated(Entity\Product $product, $limit = 5) { $cats = array_map(function ($category) { return $category['id']; }, $product->getCategories()); $tags = array_map(function ($tag) { return $tag['id']; }, $product->getTags()); // Only get related posts that are in stock & visible $query = array('posts_per_page' => $limit, 'post__not_in' => array($product->getId()), 'post_type' => Types::PRODUCT, 'orderby' => 'rand', 'meta_query' => array(array('key' => 'visibility', 'value' => array(Entity\Product::VISIBILITY_CATALOG, Entity\Product::VISIBILITY_PUBLIC), 'compare' => 'IN')), 'tax_query' => array('relation' => 'OR')); if (!empty($cats)) { $query['tax_query'][] = array('taxonomy' => Types::PRODUCT_CATEGORY, 'terms' => $cats, 'operator' => 'IN'); } if (!empty($tags)) { $query['tax_query'][] = array('taxonomy' => Types::PRODUCT_TAG, 'terms' => $tags, 'operator' => 'IN'); } return new \WP_Query($query); }