@xenonhammer

Как реализовать модуль для товаров из одной категории в opencart 2.3?

Хочу создать модуль, который бы выводил товары только одной категории. Модуль Рекомендуемые выводит товары которые ты ему дашь. Взял его за основу. у меня в магазине 40 тысяч товаров.
. Я так понял, что нужно подставить вместо массива со всеми товарами, массив с товарами имеющими id, нужной мне категории? в featured.php как я понял такая структура:
Сначала грузятся текстовые поля
$this->load->language('extension/module/featured');

Затем модуль товаров
$this->load->model('catalog/product');
Затем модуль картинок
$this->load->model('tool/image');
Далее объявляется массив с товарами которые и будут выводиться модулем
$data['products'] = array();
Как мне кажется нужно добавить проверку на нужный мне category_id
подскажите как это должно выглядить, у меня мало опыта, пытаюсь учится
Исходник featured.php
<?php
class ControllerExtensionModuleFeatured extends Controller {
	public function index($setting) {
		$this->load->language('extension/module/featured');

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_tax'] = $this->language->get('text_tax');

		$data['button_cart'] = $this->language->get('button_cart');
		$data['button_wishlist'] = $this->language->get('button_wishlist');
		$data['button_compare'] = $this->language->get('button_compare');

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

		$this->load->model('tool/image');

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

		if (!$setting['limit']) {
			$setting['limit'] = 4;
		}

		if (!empty($setting['product'])) {
			$products = array_slice($setting['product'], 0, (int)$setting['limit']);

			foreach ($products as $product_id) {
				$product_info = $this->model_catalog_product->getProduct($product_id);

				if ($product_info) {
					if ($product_info['image']) {
						$image = $this->model_tool_image->resize($product_info['image'], $setting['width'], $setting['height']);
					} else {
						$image = $this->model_tool_image->resize('placeholder.png', $setting['width'], $setting['height']);
					}

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

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

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

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

					$data['products'][] = array(
						'product_id'  => $product_info['product_id'],
						'thumb'       => $image,
						'name'        => $product_info['name'],
						'description' => utf8_substr(strip_tags(html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get($this->config->get('config_theme') . '_product_description_length')) . '..',
						'price'       => $price,
						'special'     => $special,
						'tax'         => $tax,
						'rating'      => $rating,
						'href'        => $this->url->link('product/product', 'product_id=' . $product_info['product_id'])
					);
				}
			}
		}

		if ($data['products']) {
			return $this->load->view('extension/module/featured', $data);
		}
	}
}

Если Вам покажется, что я прошу все сделать за меня, то имейте ввиду, что это не так. Учусь сам и наставников нет.
  • Вопрос задан
  • 373 просмотра
Решения вопроса 1
lazuren
@lazuren
Упрощенный вариант выглядит примерно так:
// Подключаете модель товаров
$this->load->model('catalog/product');

 
//Настраиваете фильтр (Откуда все это берется смотрите в контроллере category.php)
$filter_data = array(
    'filter_category_id' => 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);


С более полной версией ознакомьтесь в контроллере category.php
catalog/controller/product/category.php
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы