问题
I'm using OpenCart V1.5.3.1 and am trying to randomize or shuffle the products per category on page load. The other sort options should still work though (per price, rating, alphabetical,..).
Anybody that can give me some pointers?
Many thanks, Steven
Code I've tried: In controller/catalog/product/category.php
Just below
$this->data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, 100) . '..',
'price' => $price,
'special' => $special,
'tax' => $tax,
'rating' => $result['rating'],
'reviews' => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
'href' => $this->url->link('product/product', 'path=' . $this->request->get['path'] . '&product_id=' . $result['product_id'])
);
I added:
shuffle($this->data['products']);
In stead of this I also tried this: Just below:
$results = $this->model_catalog_product->getProducts($data);
I added:
srand((float)microtime() * 1000000);
shuffle($results);
$results = array_slice($results, 0, $data['limit']);
Both these methods unfortunately shuffle also the results when choosing another sorting option (rating, pricing, name). I only want the initial results on page load to be shuffled.
回答1:
The solution:
Go to catalog/model/catalog/product.php
and find the method getProducts($data)
.
Here change this:
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') {
$sql .= " ORDER BY LCASE(" . $data['sort'] . ")";
} else {
$sql .= " ORDER BY " . $data['sort'];
}
} else {
$sql .= " ORDER BY p.sort_order";
}
to this:
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') {
$sql .= " ORDER BY LCASE(" . $data['sort'] . ")";
} else {
$sql .= " ORDER BY " . $data['sort'];
}
} else {
$sql .= " ORDER BY RAND()";
}
(hint: only the last $sql .= ...
changed)
By this simple change if there is no sorting chosen the products will always be sorted in random order.
来源:https://stackoverflow.com/questions/13659495/randomize-default-products-in-opencart