The changes set forth below will cause OpenCart to assign a random product image from the category as the category image if one has not already been set. If the category contains no products, no_image.jpg
will still display.
Make the following changes around line 112 of catalog/controller/product/category.php
.
foreach ($results as $result) { if ($result['image']) { $image = $result['image']; } else { /* START AUTOMATIC CATEGORY IMAGES */ $catimg = $this->model_catalog_product->getRandomProductImageByCategoryId($result['category_id']); if($catimg){ $image = $catimg['image']; }else{ $image = 'no_image.jpg'; } /* END AUTOMATIC CATEGORY IMAGES */ } $this->data['categories'][] = array( 'name' => $result['name'], 'href' => $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'] . '_' . $result['category_id'] . $url), 'thumb' => $this->model_tool_image->resize($image, $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height')) ); } |
Add this function to catalog/model/catalog/product.php
.
public function getRandomProductImageByCategoryId($category_id) { $sql = "SELECT p.image FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (p.product_id = p2c.product_id) WHERE p.status = '1' AND p.image != '' AND p.date_available <= NOW() AND p2c.category_id = '" . (int)$category_id . "' ORDER BY RAND() LIMIT 1"; $query = $this->db->query($sql); return $query->row; } |
That’s it, enjoy your automatically generated and random category images!