Opencart 3.0 — Display All Products from Category

2020-05-03 11:55发布

I switched over to Opencart 3.0.. Not to fond of the .tpl to .twig changes.

Anyways, I have been trying, to no avail, to display all products from a particular category on another category page.

I found this foreach loop:

{% for product in products %}

Which I imagine reads

<?php foreach ($products as $product) { //do something } ?>

I tried adding the Loop to the path:

catalog/view/theme/*/template/product/category.twig

but it only shows the products from the current category page id I am currently on.

Any help would be greatly appreciated.

1条回答
欢心
2楼-- · 2020-05-03 12:52

It's generally bad practise on OC to edit the files directly, rather look at OCMOD or VQMOD to make runtime changes but not edit the core file. Granted this may be an additional complication right now.

If you look at the category.php file in the /catalog/controller/product/ folder around line 150, you'll see these lines of code:

$data['products'] = array();

$filter_data = array(
    'filter_category_id' => $category_id,
    'filter_filter'      => $filter,
    'sort'               => $sort,
    'order'              => $order,
    'start'              => ($page - 1) * $limit,
    'limit'              => $limit
);

$product_total = $this->model_catalog_product->getTotalProducts($filter_data);

$results = $this->model_catalog_product->getProducts($filter_data);

What you need to do is create a new $filter_data variable with your requisite filters, you can just have the category ID if that's all you need.

Look at the line below:

$results = $this->model_catalog_product->getProducts($filter_data);

It's calling the method getProducts which is located in the model CatalogCategory (/catalog/model/product.php) this method will build a SQL query based on the filters passed to the method and return an associative array with the results (hence the aptly named $results variable).

The controller file we first looked at then iterates through these $results and stores the values in $data['products'].

Putting this together, you can try the following:

$data['products2'] = array();

$new_filter_data = array(
    'filter_category_id' => 13 // or any relevant ID
);

$results2 = $this->model_catalog_product->getProducts($new_filter_data);

This isn't a complete solution as the controller file continues to resize images, get reviews etc. So you'll need to adjust this according to what your needs are and play around a little.

Just make sure you're working on a local copy of the site!

查看更多
登录 后发表回答