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

时间:2015-12-04 11:09:25

标签: php opencart opencart2.x

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

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

1 个答案:

答案 0 :(得分:1)

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

$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中显示。