получить список всех категорий и подкатегорий, если из идентификатора магазина в открытой корзине

У меня есть несколько магазинов opencart2. Я пытаюсь создать меню, в котором показаны все магазины со всеми их категориями и подкатегориями. Что-то вроде этого

store 1

  --cat 1

----subcat1

----subcat2

и так далее

Я знаю, что есть модуль Store, но он возвращает только список всех магазинов (shop name, shop id, shop url), а не категории. Есть ли способ вызвать категории и подкатегории из идентификатора магазина или что-то в этом роде?


person Aleksandra Chuprova    schedule 09.02.2017    source источник


Ответы (2)


Все коды, которые вам нужны, уже существуют в файлах OpenCart. Например, вы можете перейти к: catalog/model/catalog/category.php и создать копию функции getCategories, переименовать и отредактировать ее.

Я создал скрипт vQmod, который выполняет желаемую вами задачу. Если вы не используете vQmod, вы можете преобразовать его в ocmod или отредактировать файлы вручную. Вот скриншот результата: введите здесь описание изображения

И xml-файл:

<?xml version="1.0" encoding="UTF-8"?>
<modification>
    <id>Stores List With Their Categories</id>
    <version>2.x</version>
    <vqmver>2.6.0</vqmver>
    <author>[email protected]</author>

    <file name="catalog/controller/module/store.php">
        <operation error="skip">
            <search position="replace" index="1"><![CDATA[$data['stores'][] = array(]]></search>
            <add><![CDATA[
                $this->load->model('catalog/category');
                $this->load->model('catalog/product');

                $store_categories = array();
                $categories = $this->model_catalog_category->getStoreCategories(0);

                foreach ($categories as $category) {
                    // Level 2
                    $children_data = array();

                    $children = $this->model_catalog_category->getStoreCategories(0, $category['category_id']);

                    foreach ($children as $child) {
                        $filter_data = array(
                            'filter_category_id'  => $child['category_id'],
                            'filter_sub_category' => true
                        );

                        $children_data[] = array(
                            'name'  => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                            'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
                        );
                    }

                    // Level 1
                    $store_categories[] = array(
                        'name'     => $category['name'],
                        'children' => $children_data,
                        'column'   => $category['column'] ? $category['column'] : 1,
                        'href'     => $this->url->link('product/category', 'path=' . $category['category_id'])
                    );
                }

                $data['stores'][] = array(
                    'categories' => $store_categories,
            ]]></add>
        </operation>
        <operation error="skip">
            <search position="replace" index="2"><![CDATA[$data['stores'][] = array(]]></search>
            <add><![CDATA[
                $store_categories = array();
                $categories = $this->model_catalog_category->getStoreCategories($result['store_id']);

                foreach ($categories as $category) {
                        // Level 2
                        $children_data = array();

                        $children = $this->model_catalog_category->getStoreCategories($result['store_id'], $category['category_id']);

                        foreach ($children as $child) {
                            $filter_data = array(
                                'filter_category_id'  => $child['category_id'],
                                'filter_sub_category' => true
                            );

                            $children_data[] = array(
                                'name'  => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                                'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
                            );
                        }

                        // Level 1
                        $store_categories[] = array(
                            'name'     => $category['name'],
                            'children' => $children_data,
                            'column'   => $category['column'] ? $category['column'] : 1,
                            'href'     => $this->url->link('product/category', 'path=' . $category['category_id'])
                        );
                }
                $data['stores'][] = array(
                    'categories' => $store_categories,
            ]]></add>
        </operation>
    </file>

    <file name="catalog/view/theme/*/template/module/store.tpl">
        <operation error="skip">
            <search position="after"><![CDATA[<?php echo $store['name']; ?>]]></search>
            <add><![CDATA[
                <?php if ($store['categories']) { ?>
                      <ul>
                        <?php foreach ($store['categories'] as $category) { ?>
                            <li><a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a>
                            <?php if ($category['children']) { ?>
                                  <?php foreach (array_chunk($category['children'], ceil(count($category['children']) / $category['column'])) as $children) { ?>
                                  <ul>
                                    <?php foreach ($children as $child) { ?>
                                    <li><a href="<?php echo $child['href']; ?>"><?php echo $child['name']; ?></a></li>
                                    <?php } ?>
                                  </ul>
                                  <?php } ?>
                            <?php } ?>
                            </li>
                        <?php } ?>
                      </ul>
                <?php } ?>
            ]]></add>
        </operation>
    </file>

    <file name="catalog/model/catalog/category.php">
        <operation error="skip">
            <search position="before"><![CDATA[public function getCategories($parent_id = 0) {]]></search>
            <add><![CDATA[
                public function getStoreCategories($store_id, $parent_id = 0) {
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) LEFT JOIN " . DB_PREFIX . "category_to_store c2s ON (c.category_id = c2s.category_id) WHERE c.parent_id = '" . (int)$parent_id . "' AND cd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND c2s.store_id = '" . (int)$store_id . "'  AND c.status = '1' ORDER BY c.sort_order, LCASE(cd.name)");

                    return $query->rows;
                }
            ]]></add>
        </operation>
    </file>

</modification>

Изменить: вот версия ocmod, проверенная на opencart 2.0.3.1 с темой по умолчанию.

Для загрузки файла OCMOD расширение файла должно быть либо .ocmod.zip, либо .ocmod.xml. Это делается для того, чтобы никакие файлы OCMOD не загружались администратору пользователей магазина.

<?xml version="1.0" encoding="UTF-8"?>
<modification>
    <name>Stores List With Their Categories</name>
    <version>2.x</version>
    <author>[email protected]</author>
    <code>Stores List With Their Categories</code>

    <file path="catalog/controller/module/store.php">
        <operation>
            <search index="0"><![CDATA[$data['stores'][] = array(]]></search>
            <add position="replace"><![CDATA[
                $this->load->model('catalog/category');
                $this->load->model('catalog/product');

                $store_categories = array();
                $categories = $this->model_catalog_category->getStoreCategories(0);

                foreach ($categories as $category) {
                    // Level 2
                    $children_data = array();

                    $children = $this->model_catalog_category->getStoreCategories(0, $category['category_id']);

                    foreach ($children as $child) {
                        $filter_data = array(
                            'filter_category_id'  => $child['category_id'],
                            'filter_sub_category' => true
                        );

                        $children_data[] = array(
                            'name'  => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                            'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
                        );
                    }

                    // Level 1
                    $store_categories[] = array(
                        'name'     => $category['name'],
                        'children' => $children_data,
                        'column'   => $category['column'] ? $category['column'] : 1,
                        'href'     => $this->url->link('product/category', 'path=' . $category['category_id'])
                    );
                }

                $data['stores'][] = array(
                    'categories' => $store_categories,
            ]]></add>
        </operation>
        <operation>
            <search index="1"><![CDATA[$data['stores'][] = array(]]></search>
            <add position="replace"><![CDATA[
                $store_categories = array();
                $categories = $this->model_catalog_category->getStoreCategories($result['store_id']);

                foreach ($categories as $category) {
                        // Level 2
                        $children_data = array();

                        $children = $this->model_catalog_category->getStoreCategories($result['store_id'], $category['category_id']);

                        foreach ($children as $child) {
                            $filter_data = array(
                                'filter_category_id'  => $child['category_id'],
                                'filter_sub_category' => true
                            );

                            $children_data[] = array(
                                'name'  => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                                'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
                            );
                        }

                        // Level 1
                        $store_categories[] = array(
                            'name'     => $category['name'],
                            'children' => $children_data,
                            'column'   => $category['column'] ? $category['column'] : 1,
                            'href'     => $this->url->link('product/category', 'path=' . $category['category_id'])
                        );
                }
                $data['stores'][] = array(
                    'categories' => $store_categories,
            ]]></add>
        </operation>
    </file>

    <file path="catalog/view/theme/*/template/module/store.tpl">
        <operation>
            <search><![CDATA[<?php echo $store['name']; ?>]]></search>
            <add position="after"><![CDATA[
                <?php if ($store['categories']) { ?>
                      <ul>
                        <?php foreach ($store['categories'] as $category) { ?>
                            <li><a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a>
                            <?php if ($category['children']) { ?>
                                  <?php foreach (array_chunk($category['children'], ceil(count($category['children']) / $category['column'])) as $children) { ?>
                                  <ul>
                                    <?php foreach ($children as $child) { ?>
                                    <li><a href="<?php echo $child['href']; ?>"><?php echo $child['name']; ?></a></li>
                                    <?php } ?>
                                  </ul>
                                  <?php } ?>
                            <?php } ?>
                            </li>
                        <?php } ?>
                      </ul>
                <?php } ?>
            ]]></add>
        </operation>
    </file>

    <file path="catalog/model/catalog/category.php">
        <operation>
            <search><![CDATA[public function getCategories($parent_id = 0) {]]></search>
            <add position="before"><![CDATA[
                public function getStoreCategories($store_id, $parent_id = 0) {
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) LEFT JOIN " . DB_PREFIX . "category_to_store c2s ON (c.category_id = c2s.category_id) WHERE c.parent_id = '" . (int)$parent_id . "' AND cd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND c2s.store_id = '" . (int)$store_id . "'  AND c.status = '1' ORDER BY c.sort_order, LCASE(cd.name)");

                    return $query->rows;
                }
            ]]></add>
        </operation>
    </file>

</modification>

См. эту хорошую статью о различиях vqmod и ocmod: https://forum.opencart.com/viewtopic.php?f=24&t=131995

person DigitCart    schedule 10.02.2017
comment
Вау, это отличная помощь! Ты мой герой! Однако я не очень разбираюсь в opencart... поэтому мне потребуется время, чтобы понять реализацию кода... Мне также нужно преобразовать его в ocmod. Я также не могу найти хорошую документацию по файлу ocmod. Единственное, что я нашел, это ссылка Например, что означает error=skip ( хотя в ocmod я этого атрибута не увидел)? Или индексный атрибут? Вы знаете, где я могу найти больше информации об использовании ocmod? Но большое спасибо за помощь! - person Aleksandra Chuprova; 10.02.2017
comment
Привет! Пожалуйста. Почему бы вам не использовать vQmod? Я скоро добавлю версию ocmod в свой пост. - person DigitCart; 10.02.2017
comment
У моего работодателя есть другой разработчик, который рекомендует использовать ocmod... Мне нечего сказать по этому поводу... И еще раз спасибо! Хороших выходных! - person Aleksandra Chuprova; 10.02.2017
comment
Я преобразовал файл xml из вашего ответа в ocmod. Мне также нужно загрузить вывод модуля Stores в меню. Поэтому я добавил код внизу, чтобы сделать это. Это правильный способ сделать это? Я не знаю, хорошо ли это размещать здесь - преобразованный файл с добавленными строками? Хм, я сделаю это в качестве ответа, я был бы признателен, если бы вы могли просмотреть его ... - person Aleksandra Chuprova; 13.02.2017

Я преобразовал XML-файл @Mojtaba Sabeti в файл ocmod.

Я сомневаюсь в атрибуте index. Я где-то читал, что в ocmod индекс начинается с «0». поэтому первое вхождение будет index="0". Это правильно?

Мне также нужно загрузить выходные данные модуля Stores в файл шаблона меню. Поэтому я добавил пару строк внизу модификации, чтобы сделать это. Я в основном пытаюсь загрузить контроллер модуля Stores в контроллер Menu. Я делаю это прямо перед загрузкой файла шаблона. Контроллер меню находится по адресу catalog/controller/journal2/menu.php Это правильный путь?

  <?xml version="1.0" encoding="UTF-8"?>
<modification>
<id>Stores List With Their Categories</id>
<version>2.x</version>
<vqmver>2.6.0</vqmver>
<author>[email protected]</author>

<file path="catalog/controller/module/store.php">
    <operation>
        <search><![CDATA[$data['stores'][] = array(]]></search>
        <add position="replace" index="1"><![CDATA[
            $this->load->model('catalog/category');
            $this->load->model('catalog/product');

            $store_categories = array();
            $categories = $this->model_catalog_category->getStoreCategories(0);

            foreach ($categories as $category) {
                // Level 2
                $children_data = array();

                $children = $this->model_catalog_category->getStoreCategories(0, $category['category_id']);

                foreach ($children as $child) {
                    $filter_data = array(
                        'filter_category_id'  => $child['category_id'],
                        'filter_sub_category' => true
                    );

                    $children_data[] = array(
                        'name'  => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                        'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
                    );
                }

                // Level 1
                $store_categories[] = array(
                    'name'     => $category['name'],
                    'children' => $children_data,
                    'column'   => $category['column'] ? $category['column'] : 1,
                    'href'     => $this->url->link('product/category', 'path=' . $category['category_id'])
                );
            }

            $data['stores'][] = array(
                'categories' => $store_categories,
        ]]></add>
    </operation>
    <operation>
        <search><![CDATA[$data['stores'][] = array(]]></search>
        <add position="replace" index="2"><![CDATA[
            $store_categories = array();
            $categories = $this->model_catalog_category->getStoreCategories($result['store_id']);

            foreach ($categories as $category) {
                    // Level 2
                    $children_data = array();

                    $children = $this->model_catalog_category->getStoreCategories(0, $category['category_id']);

                    foreach ($children as $child) {
                        $filter_data = array(
                            'filter_category_id'  => $child['category_id'],
                            'filter_sub_category' => true
                        );

                        $children_data[] = array(
                            'name'  => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                            'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
                        );
                    }

                    // Level 1
                    $store_categories[] = array(
                        'name'     => $category['name'],
                        'children' => $children_data,
                        'column'   => $category['column'] ? $category['column'] : 1,
                        'href'     => $this->url->link('product/category', 'path=' . $category['category_id'])
                    );
            }
            $data['stores'][] = array(
                'categories' => $store_categories,
        ]]></add>
    </operation>
</file>

<file path="catalog/view/theme/*/template/module/store.tpl">
    <operation error="skip">
        <search position="after"><![CDATA[<?php echo $store['name']; ?>]]></search>
        <add><![CDATA[
            <?php if ($store['categories']) { ?>
                  <ul>
                    <?php foreach ($store['categories'] as $category) { ?>
                        <li><a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a>
                        <?php if ($category['children']) { ?>
                              <?php foreach (array_chunk($category['children'], ceil(count($category['children']) / $category['column'])) as $children) { ?>
                              <ul>
                                <?php foreach ($children as $child) { ?>
                                <li><a href="<?php echo $child['href']; ?>"><?php echo $child['name']; ?></a></li>
                                <?php } ?>
                              </ul>
                              <?php } ?>
                        <?php } ?>
                        </li>
                    <?php } ?>
                  </ul>
            <?php } ?>
        ]]></add>
    </operation>
</file>

<file path="catalog/model/catalog/category.php">
    <operation>
        <search><![CDATA[public function getCategories($parent_id = 0) {]]></search>
        <add position="before"><![CDATA[
            public function getStoreCategories($store_id, $parent_id = 0) {
                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) LEFT JOIN " . DB_PREFIX . "category_to_store c2s ON (c.category_id = c2s.category_id) WHERE c.parent_id = '" . (int)$parent_id . "' AND cd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND c2s.store_id = '" . (int)$store_id . "'  AND c.status = '1' ORDER BY c.sort_order, LCASE(cd.name)");

                return $query->rows;
            }
        ]]></add>
    </operation>
</file>

<file path="catalog/controller/journal2/menu.php">
    <operation>
    <search><![CDATA[$this->template = $this->config->get('config_template') . '/template/journal2/menu/main.tpl';]]></search>
    <add position="before"><![CDATA[
    $data['ac_all_stores'] = $this->load->controller('module/store');
    ]]></add>
    </operation>
</file>

person Aleksandra Chuprova    schedule 13.02.2017
comment
Привет, я добавил версию ocmod в свой ответ. проверьте его и дайте мне знать, если у вас есть какие-либо проблемы. чтобы отобразить список магазинов в верхнем меню, откройте новую тему. - person DigitCart; 14.02.2017