Here is my solution:
On catalog/controller/product/product.php, after line ~394:
Code: Select all
$results = $this->model_catalog_product->getProductRelated($this->request->get['product_id']);
Code: Select all
########## INSERT RELATED PRODUCTS BASED ON PRODUCT CATEGORIES ===== BEGIN ##########
//create an array to insert all new related products found on queries
$all_related_products_from_categories = [];
//set total quantity of related products - note that the manual related products
//set on product admin page will be displayed first, so the total amount of products can be higher than this
$total_products_to_show = 20;
//find this products categories
$product_categories = $this->model_catalog_product->getCategories($data['product_id']);
//find each category´s products
foreach($product_categories as $pc){
//get category´s products
$related_products_from_category = $this->model_catalog_product->getProducts(['filter_category_id' => $pc['category_id']]);
//insrt into array
foreach($related_products_from_category as $rpc){
$all_related_products_from_categories[] = $rpc;
}
}
//if the quantity of products found before is lower than the desired amount of related products, get random products to add
if(count($all_related_products_from_categories) < $total_products_to_show){
//find random products (needs improvement - right now it is only getting the first products - need to find a way to be really random)
$random_products = $this->model_catalog_product->getProducts(['limit' => $total_products_to_show-count($all_related_products_from_categories)]);
//merge with products from categories
$auto_related_products = array_merge($all_related_products_from_categories, $random_products);
} else {
//if the desired amount is already met, just keep going
$auto_related_products = $all_related_products_from_categories;
}
$count = 0;
//foreach product found on previous queries
foreach($auto_related_products as $arp){
//break loop if reaches the desired amount
if($count > $total_products_to_show){ break; }
//check if product has stock and it is not the same as product on page
if($arp['product_id'] == $this->request->get['product_id'] || $arp['quantity'] < 1){ continue; }
//insert in $results array, which will be used at the related
//products section of the page alongside the manually defined related products of this product
$results[$arp['product_id']] = $arp;
$count++;
}
########## INSERT RELATED PRODUCTS BASED ON PRODUCT CATEGORIES ===== END ##########