如何在 OpenCart 2 中显示某个类别的项目?

How to display items of a certain category in OpenCart 2?

我需要在 OpenCart 2 的主页上显示某个类别的项目。我该怎么做? 我来自控制器的代码:

   $products_info = $this->model_catalog_product->getProducts();
   $data['products'] = $products_info;

假设您首先加载了您正在调用的模型:

$this->load->model('catalog/product');

您需要做的就是定义一组要传递给 getProducts() 的设置。在这种情况下,您可以只发送您想要为其获取产品的类别 ID:

$filter_data = array(
    'filter_category_id' => $category_id,
);

然后像你一样调用函数:

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

然后像在类别视图中一样遍历产品以将数据传递到视图:

foreach ($results as $result) {
    if ($result['image']) {
        $image = $this->model_tool_image->resize($result['image'], $this->config->get('config_image_product_width'), $this->config->get('config_image_product_height'));
    } else {
        $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('config_image_product_width'), $this->config->get('config_image_product_height'));
    }

    if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
        $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
    } else {
        $price = false;
    }

    if ((float)$result['special']) {
        $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
    } else {
        $special = false;
    }

    if ($this->config->get('config_tax')) {
        $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price']);
    } else {
        $tax = false;
    }

    if ($this->config->get('config_review_status')) {
        $rating = (int)$result['rating'];
    } else {
        $rating = false;
    }

    $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, $this->config->get('config_product_description_length')) . '..',
        'price'       => $price,
        'special'     => $special,
        'tax'         => $tax,
        'minimum'     => $result['minimum'] > 0 ? $result['minimum'] : 1,
        'rating'      => $result['rating'],
        'href'        => $this->url->link('product/product', 'path=' . $this->request->get['path'] . '&product_id=' . $result['product_id'] . $url)
    );
}

现在您可以根据自己的喜好在 tpl 中展示一系列产品。