WC_Product_Data_Store_CPT::get_related_products_query PHP Method

    public function get_related_products_query($cats_array, $tags_array, $exclude_ids, $limit)
    {
        global $wpdb;
        // Arrays to string.
        $exclude_ids = implode(',', array_map('absint', $exclude_ids));
        $cats_array = implode(',', array_map('absint', $cats_array));
        $tags_array = implode(',', array_map('absint', $tags_array));
        $limit = absint($limit);
        $query = array();
        $query['fields'] = "SELECT DISTINCT ID FROM {$wpdb->posts} p";
        $query['join'] = " INNER JOIN {$wpdb->postmeta} pm ON ( pm.post_id = p.ID AND pm.meta_key='_visibility' )";
        $query['join'] .= " INNER JOIN {$wpdb->term_relationships} tr ON (p.ID = tr.object_id)";
        $query['join'] .= " INNER JOIN {$wpdb->term_taxonomy} tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)";
        $query['join'] .= " INNER JOIN {$wpdb->terms} t ON (t.term_id = tt.term_id)";
        if ('yes' === get_option('woocommerce_hide_out_of_stock_items')) {
            $query['join'] .= " INNER JOIN {$wpdb->postmeta} pm2 ON ( pm2.post_id = p.ID AND pm2.meta_key='_stock_status' )";
        }
        $query['where'] = ' WHERE 1=1';
        $query['where'] .= " AND p.post_status = 'publish'";
        $query['where'] .= " AND p.post_type = 'product'";
        $query['where'] .= " AND p.ID NOT IN ( {$exclude_ids} )";
        $query['where'] .= " AND pm.meta_value IN ( 'visible', 'catalog' )";
        if ('yes' === get_option('woocommerce_hide_out_of_stock_items')) {
            $query['where'] .= " AND pm2.meta_value = 'instock'";
        }
        if ($cats_array || $tags_array) {
            $query['where'] .= ' AND (';
            if ($cats_array) {
                $query['where'] .= " ( tt.taxonomy = 'product_cat' AND t.term_id IN ( {$cats_array} ) ) ";
                if ($tags_array) {
                    $query['where'] .= ' OR ';
                }
            }
            if ($tags_array) {
                $query['where'] .= " ( tt.taxonomy = 'product_tag' AND t.term_id IN ( {$tags_array} ) ) ";
            }
            $query['where'] .= ')';
        }
        $query['limits'] = " LIMIT {$limit} ";
        return $query;
    }