0

我正在构建一个仅以 2 种产品开始的网站,因此类别菜单不合适,我正在尝试创建仅产品菜单。

我使用的是商业主题,它会自动在 header.tpl 中生成一个类别菜单

我需要创建一个产品菜单,但不是一个 php 编码器,它变得很棘手,到目前为止我有:

<ul id="topnav">
<?php foreach ($products as $product) { ?>
<li><a href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?></a></li>
<?php } ?>
</ul>

有谁知道我要去哪里错了?

4

2 回答 2

2

Opencart 使用模型-视图-控制器框架 (MVC),其中控制器与模型对话以检索数据,准备数据,然后将其传递给视图(Opencart 中的 .tpl 文件),然后适当地显示它。

在您的情况下, header.tpl 没有 $products 数组的数据,因为它尚未在 header.php 控制器中准备好。因此,在标头控制器(catalog/controller/header.php)的 index() 函数中,让我们从模型中获取所有数据,按照我们想要的方式进行准备,然后将其传递给视图:

$this->load->model('catalog/category');   //
$this->load->model('catalog/product');    //Load our models so the controller can get data
$categories = $this->model_catalog_category->getCategories(0);  //get all top level categories
$all_products = array();
foreach ($categories as $category)  //go through each category and get all the products for each category
{
$category_products = $this->model_catalog_product->getProductsforCategoryId($category['category_id']); //returns product IDs for category
foreach ($category_products as $category_product)
{
    $product_data = $this->model_catalog_product->getProduct($category_product);   //fetch product data for this product then add it to our array of all products
    $all_products[] = array(
        'href'        => $this->url->link('product/product', 'product_id=' . $product_data['product_id']),
        'name'        => $product_data['name']
    );
}
}
$this->data['products'] = $all_products;  //Now pass our product array data to the view, in the view this will be the $products array

这是假设您的所有产品仅属于顶级类别而不属于任何子类别。如果您将来确实创建了顶级类别的子类别,您将需要遍历这些子类别并获取每个子类别的产品。

于 2012-08-28T21:35:57.260 回答
0

感谢 OpenCart 论坛的一位好心成员,我找到了答案。

只需将此代码放在您需要的地方:

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

    $products_1 = $this->model_catalog_product->getProducts($data = array());                                   
    if ($products_1) {$output = '<ul id="topnav">';}                                               
    foreach ($products_1 as $product_1) {                                                         
       $output .= '<li>';                                                                                                         
       $unrewritten  = $this->url->link('product/product', 'product_id=' . $product_1['product_id']);                        
       $output .= '<a href="'.($unrewritten).'">' . $product_1['model'] . '</a>';                        
    }
    if ($products_1) {$output .= '</ul>';}                                             
    echo $output;                                                          
    ?>

归功于这里的论坛成员。

于 2012-09-03T03:53:02.070 回答