Оценок: 3
Изображения товара Opencart с прокруткой

Изображения товара Opencart с прокруткой

Изначально на странице товара выводится основное изображение + дополнительные. После изменений будут выводится все изображения товара без разделения. Для каждого - миниатюра, среднее и большое изображение.

В блок фото будет добавлена навигация вперед - назад, так же переключать изображения можно будет по клику на миниатюру.

Изменения в контроллере товара

Находим следующий код (пример для opencart 2, для opencart 3 выглядит похоже):

if ($product_info['image']) {
				$data['popup'] = $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height'));
			} else {
				$data['popup'] = '';
			}

			if ($product_info['image']) {
				$data['thumb'] = $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_thumb_width'), $this->config->get($this->config->get('config_theme') . '_image_thumb_height'));
			} else {
				$data['thumb'] = '';
			}

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

			$results = $this->model_catalog_product->getProductImages($this->request->get['product_id']);

			foreach ($results as $result) {
				$data['images'][] = array(
					'popup' => $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height')),
					'thumb' => $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_additional_width'), $this->config->get($this->config->get('config_theme') . '_image_additional_height'))
				);
			}

Вносим изменения: убираем $data['thumb'] и $data['popup'] (при этом из шаблона исчезнут соответствующие переменные), основное изображение выведем в $data['images'], где теперь будет три размера - popup, bthumb, thumb. Добавим так же переменную $imgnum для вывода номера изображения и их количества.

Для начала, Opencart 2

$this->load->model('tool/image');
			$data['images'] = array();
			$imgnum = 0;
			if ($product_info['image']) {
				$imgnum = 1;
				$data['images'][] = array(
					'popup' => $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height')),
					'bthumb' => $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_thumb_width'), $this->config->get($this->config->get('config_theme') . '_image_thumb_height')),
					'thumb' => $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_additional_width'), $this->config->get($this->config->get('config_theme') . '_image_additional_height')),
					'imgnum' => $imgnum
				);
			}
			$results = $this->model_catalog_product->getProductImages($this->request->get['product_id']);
			foreach ($results as $result) {
				$imgnum++;
				$data['images'][] = array(
					'popup' => $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height')),
					'bthumb' => $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_thumb_width'), $this->config->get($this->config->get('config_theme') . '_image_thumb_height')),
					'thumb' => $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_additional_width'), $this->config->get($this->config->get('config_theme') . '_image_additional_height')),
					'imgnum' => $imgnum
				);
			}
			$data['imgnum'] = $imgnum;

При таком варианте, столкнулся с неожиданной ошибкой в одном SEO модуле. Оказывается, этому модулю очень нужен был $data['thumb'], поэтому код для опенкарт 3 будет отличаться не только путем получения размеров изображения. Что бы избежать ошибок, я сначала объявлю $data['thumb'] и $data['popup'], а после их значения использую в массиве. Посмотрите, сравните.

Тоже самое для Opencart 3

$this->load->model('tool/image');
			$data['images'] = array();
			$imgnum = 0;
			if ($product_info['image']) {
				$imgnum = 1;
				$data['popup'] = $this->model_tool_image->resize($product_info['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_popup_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_popup_height'));
				$data['thumb'] = $this->model_tool_image->resize($product_info['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_thumb_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_thumb_height'));
				$data['images'][] = array(
					'popup' => $data['popup'],
					'bthumb' => $data['thumb'],
					'thumb' => $this->model_tool_image->resize($product_info['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_additional_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_additional_height')),
					'imgnum' => $imgnum
				);
			}

			$results = $this->model_catalog_product->getProductImages($this->request->get['product_id']);

			foreach ($results as $result) {
				$imgnum++;
				$data['images'][] = array(
					'popup' => $this->model_tool_image->resize($result['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_popup_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_popup_height')),
					'bthumb' => $this->model_tool_image->resize($result['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_thumb_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_thumb_height')),
					'thumb' => $this->model_tool_image->resize($result['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_additional_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_additional_height')),
					'imgnum' => $imgnum
				);
			}
			$data['imgnum'] = $imgnum;

Изменения в шаблоне - product.tpl (Opencart 2)

Здесь для Opencart 2, ниже будет для третьего. Меняем следующий блок:

<?php if ($thumb || $images) { ?>
          <ul class="thumbnails">
            <?php if ($thumb) { ?>
            <li><a class="thumbnail" href="<?php echo $popup; ?>" title="<?php echo $heading_title; ?>"><img src="<?php echo $thumb; ?>" title="<?php echo $heading_title; ?>" alt="<?php echo $heading_title; ?>" /></a></li>
            <?php } ?>
            <?php if ($images) { ?>
            <?php foreach ($images as $image) { ?>
            <li class="image-additional"><a class="thumbnail" href="<?php echo $image['popup']; ?>" title="<?php echo $heading_title; ?>"> <img src="<?php echo $image['thumb']; ?>" title="<?php echo $heading_title; ?>" alt="<?php echo $heading_title; ?>" /></a></li>
            <?php } ?>
            <?php } ?>
          </ul>
          <?php } ?>

на это:

<?php if ($images) { ?>
          <ul class="thumbnails bthumbnails">
            <?php foreach ($images as $image) { ?>
            <li class="thumb-<?php echo $image['imgnum']; if ($image['imgnum']==1) { echo ' active first';} if ($image['imgnum']==$imgnum) { echo ' last';} ?>"><a class="thumbnail" href="<?php echo $image['popup']; ?>" title="<?php echo $heading_title; ?>"><img src="<?php echo $image['bthumb']; ?>" title="<?php echo $heading_title; ?>" alt="<?php echo $heading_title; ?>" /></a></li>
            <?php } ?>
            <span class="to prev" data="prev"><i class="fa fa-chevron-left fa-3x"></i></span>
            <span class="to next" data="next"><i class="fa fa-chevron-right fa-3x"></i></span>
          </ul>
          <?php if ($imgnum > 1) { ?>
          <ul class="thumbs-additional thumbnails">
            <?php foreach ($images as $image) { ?>
            <li class="image-additional additional-<?php echo $image['imgnum']; if ($image['imgnum']==1) { echo ' active first';} ?>" data="thumb-<?php echo $image['imgnum']; ?>"><img src="<?php echo $image['thumb']; ?>" title="<?php echo $heading_title; ?>" alt="<?php echo $heading_title; ?>" /></li>
            <?php } ?>
          </ul>
          <?php } ?>
          <?php } ?>

Изменения в шаблоне - product.twig (Opencart 3)

В этой версии находим аналогичный блок, выглядит он так:

{% if thumb or images %}
          <ul class="thumbnails">
            {% if thumb %}
            <li><a class="thumbnail" href="{{ popup }}" title="{{ heading_title }}"><img src="{{ thumb }}" title="{{ heading_title }}" alt="{{ heading_title }}" /></a></li>
            {% endif %}
            {% if images %}
            {% for image in images %}
            <li class="image-additional"><a class="thumbnail" href="{{ image.popup }}" title="{{ heading_title }}"> <img src="{{ image.thumb }}" title="{{ heading_title }}" alt="{{ heading_title }}" /></a></li>
            {% endfor %}
            {% endif %}
          </ul>
          {% endif %}

Меняем на (код полностью аналогичен Opencart 2):

{% if images %}
          <ul class="thumbnails bthumbnails">
            {% for image in images %}
            <li class="thumb-{{ image.imgnum }} {% if image.imgnum == 1 %} active first{% endif %}{% if image.imgnum == imgnum %} last{% endif %}"><a class="thumbnail" href="{{ image.popup }}" title="{{ heading_title }}"><img src="{{ image.bthumb }}" title="{{ heading_title }}" alt="{{ heading_title }}" /></a></li>
            {% endfor %}
            <span class="to prev" data="prev"><i class="fa fa-chevron-left fa-3x"></i></span>
            <span class="to next" data="next"><i class="fa fa-chevron-right fa-3x"></i></span>
          </ul>
          {% if imgnum > 1 %}
          <ul class="thumbs-additional thumbnails">
            {% for image in images %}
            <li class="image-additional additional-{{ image.imgnum }} {% if image.imgnum == 1 %} active first{% endif %}" data="thumb-{{ image.imgnum }}"><img src="{{ image.thumb }}" title="{{ heading_title }}" alt="{{ heading_title }}" /></li>
            {% endfor %}
          </ul>
          {% endif %}
          {% endif %}

CSS и JS - добавляем переключение и оформляем

Для начала немного изменим/добавим стили:

.image-additional {margin-bottom: 20px;padding: 5px;display: block;border: 1px solid #ddd;}
.image-additional.active {border-color: #239ece;}
.bthumbnails {position: relative;}
.bthumbnails > li {display: none;}
.bthumbnails > li.active {display: block;}
.thumbnails .dn {display: none !important;}
.thumbnails .to {display: none;opacity: 0.5;position: absolute;top: 50%;margin-top: -25px;cursor: pointer;
	color: #fff;background: #9a9a9a;text-align: center;width: 40px;padding: 3px;}
.thumbnails .to:hover {background: #239ece;}
.thumbnails .prev {left: 0px}
.thumbnails .next {right: 0px}
.thumbnails:hover .to {display: block;}

Теперь JS, можем добавить, к примеру, в common.js:

if ($('*').is('.thumbnails')) {
		function thumbsActUp(){
			if ($('.thumbnails .last').hasClass('active')) {
    			$('.thumbnails .next').addClass('dn');
    		} else {
    			$('.thumbnails .next').removeClass('dn');
    		}

    		if ($('.thumbnails .first').hasClass('active')) {
    			$('.thumbnails .prev').addClass('dn');
    		} else {
    			$('.thumbnails .prev').removeClass('dn');
    		}
		}
		thumbsActUp();
		$('.thumbnails .to').click(function() {
    		var d = $(this).attr('data');
    		if (d == 'next' && !$(this).hasClass('dn')) {
    			$('.thumbnails .active').removeClass('active').next().addClass('active');
    		}
    		if (d == 'prev' && !$(this).hasClass('dn')) {
    			$('.thumbnails .active').removeClass('active').prev().addClass('active');
    		}
    		thumbsActUp();	
  		});
  		$('.thumbs-additional li').click(function() {
  			var to = $(this).attr('data');
  			$('.thumbnails .active').removeClass('active');
  			$(this).addClass('active');
  			$('.thumbnails .'+to).addClass('active');
  			thumbsActUp();
  		});
	}

Пример можно посмотреть вот здесь

Оценок: 3
Надежный хостинг VPS серверов
  • Свои ISO образы
  • VDS с оплатой раз и навсегда
  • Аренда VDS на любой срок, с оплатой по дням
  • Большое разнообразие конфигураций
  • Дата-центры в ЕС и России
+ скидка 10%

Комментарии (4)

  1. Отличная схема и грамотно написана. Переписал все тоже самое на OpenCart 3 и контроллер и .twig.
    Всё работает!!! Спасибо!!!

    wmdesigner 29 февраля 2020, 22:44 0
    • В готовых файлах могут другие изменения быть. Здесь только код заменить одно на другое… Могу посмотреть что не так в измененных файлах… vl@onenv.ru — вот сюда если отправите

      Владимир 05 ноября 2018, 20:05 0
      • Разобрался. мой косяск… ;)
        а как сделать, что бы можно было бесконечно тыкать в кнопки?
        а то сейчас если фото кончилось… то листай в другую сторону.

        великий_и_ужасный 05 ноября 2018, 22:02 0
      • Слей готовые файлы что ли. пожалуйста.
        решение по какой то причине не стартует.

        великий_и_ужасный 05 ноября 2018, 20:00 0