[英]How to create a product only menu in Opencart?
我正在構建一個僅以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>
有誰知道我在哪里出錯?
Opencart使用模型 - 視圖 - 控制器框架(MVC),其中Controller與模型對話以檢索數據,准備數據然后將其傳遞給View(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
這假設您的所有產品僅屬於頂級類別而不屬於任何子類別。 如果您確實在將來創建頂級類別的子類別,則需要循環遍歷這些子類別並獲取每個子類別的產品。
感謝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;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.