Как обернуть фотки в микроразметку (решение)

Опишу как обернуть фотки содержимого в микроразметку
schema.org/ImageObject
и ресайзнуть их по ширине контента с помощью плагина

Было


Стало
Александр Иванов
01 мая 2020, 05:54
modx.pro
2
875
+1

Комментарии: 2

Александр Иванов
01 мая 2020, 06:15
+1
1. Скачиваем библиотеку phpQuery
Кидаем её куда-нибудь, я залил в /assets/phpQuery
Так же потребуется phpthumbon

2. Создаем плагин с названием imageSrc
вешаем событие OnWebPagePrerender
Содержимое
<?php
switch ($modx->event->name) {
    case 'OnWebPagePrerender':
        if ( $modx->context->get( 'key' ) == 'mgr') return;
        
        // Условия для каких шаблонов мы будем это делать, у меня ID 3 - это статейные шаблоны
        $templates_allow = array(3);
        // класс обертки контента, где нужно искать фотки
        $wrapper_class = 'about-content';
        // Ваша ширина контента
        $wrapper_width = 866;
        
        $img_wrapper_min_width = 100; // минимальная ширина фотки для обертки
        
        $img_wrapper_min_width_fancybox = 1000; // минимальная ширина фотки для обертки в fancybox
        $img_wrapper_min_height_fancybox = 300; // минимальная высота фотки для обертки в fancybox
        $template = $modx->resource->get('template');
        $resource_id = $modx->resource->get('id');
        $cache_key = md5($resource_id);
        $file = MODX_BASE_PATH . 'resourcecache/u/prep_' . $cache_key . '.txt';
        if(!in_array($template,$templates_allow)) return;
        $output = &$modx->resource->_output;
             
        if(is_file($file)){
            if(!empty($cache)){
                // здесь у меня дополнительная обертка кеша
                $string = preg_replace('|<div class="'.$wrapper_class.'">(.*)</div>|isU', '<div class="'.$wrapper_class.' about-cache">'.$cache.'</div>',$output);
                $output = $string;
                return;
                break;
            }
        }
        
        include_once MODX_ASSETS_PATH . 'phpQuery/phpQuery.php';
        // здесь я удаляю пустые теги
        $output = str_replace(array('<h2> </h2>','<h3> </h3>','<h1> </h1>'),'<p> </p>',$output);
        $html = phpQuery::newDocument($output);
        // получаю картинки с условием
        $img = $html->find('.'.$wrapper_class." img:not(.aggregate__img):not(.gallery__img)");
        $i = 0;
      
        foreach($img as $value){
            $src = $value->getAttribute('src');
            $img_path = MODX_BASE_PATH.ltrim($src, "/");
            if(file_exists($img_path)){
                $img_size = getimagesize($img_path);
                $width = $img_size[0];
                $height = $img_size[1];
                $attr_width = $value->getAttribute('width');
                $attr_height = $value->getAttribute('height');
                // пропускаю фотки которые больше  px
                if($width >$img_wrapper_min_width && (isset($attr_width) && $attr_width > $img_wrapper_min_width)){
                    if($width >$wrapper_width){
                        $i++;
                        $w = 'w='.((isset($attr_width) && $attr_width < $wrapper_width) ? $attr_width :$wrapper_width);
                        $new_src = $modx->runSnippet('phpthumbon',array('input'=>$src,'options'=>$w.'&q=60&bg=ffffff'));
                        $img_mew_path = MODX_BASE_PATH.ltrim($new_src, "/");
                        $new_img_size = getimagesize($img_mew_path);
                        $new_width = $new_img_size[0];
                        $new_height = $new_img_size[1];
                        $src = $modx->runSnippet('phpthumbon',array('input'=>$src,'options'=>'q=100&f=png&bg=ffffff'));
                        $value->setAttribute('src',$new_src);
                        $value->setAttribute('data-src',$src);
                        
                        if((isset($attr_width) && $attr_width > $wrapper_width)){
                             $value->setAttribute('width',$wrapper_width);
                             $value->setAttribute('height',$new_height);
                        }else{
                            $value->setAttribute('width',$new_width);
                            $value->setAttribute('height',$new_height);
                        }
       
                        $name = $value->getAttribute('alt');
                        if(!$name){
                            $value->setAttribute('alt',($name ? $name : $modx->resource->get('pagetitle')));
                        }
                        $value = pq($value);
                      
                        $new_html = $value;
                        
                        if($new_height > $img_wrapper_min_height_fancybox && $width > $img_wrapper_min_width_fancybox || (isset($attr_width) && $attr_width!=$width) && ((isset($new_height) && $new_height!=$height && $height >$img_wrapper_min_height_fancybox))){
                            // здесь я оборачиваю большие фотки, что бы их можно было показать при помощи fancybox
                          $new_html = '<a href="'.$src.'" class="article__image" data-fancybox="article-'.$i.'">'.$new_html.'</a>';
                        }
                        
                        $new_html .='<meta itemprop="name" content="'.($name ? $name : $modx->resource->get('pagetitle')).'">';
                        $new_html .='<meta itemprop="width" content="'.$width.'">';
                        $new_html .='<meta itemprop="height" content="'.$height.'">';
                        $new_html .='<meta itemprop="contentUrl" content="'.$src.'">';
                      
                        $new_html = $value->wrap('<span itemscope="" itemtype="http://schema.org/ImageObject">'.$new_html.'</span>');
                        $value->replaceWith($new_html);
     
                    }else{
                        
                        $i++;
                        $new_src = $src;
                        $value->setAttribute('itemprop','contentUrl');
                        $name =  $value->getAttribute('alt');
                        
                        if(!$name){
                            $value->setAttribute('alt',($name ? $name : $modx->resource->get('pagetitle')));
                        }
                        
                        $value = pq($value);
                        $new_html = $value;
                        $new_html .='<meta itemprop="name" content="'.($name ? $name : $modx->resource->get('pagetitle')).'">';
                        $new_html .='<meta itemprop="width" content="'.$width.'">';
                        $new_html .='<meta itemprop="height" content="'.$height.'">';
                        $new_html = $value->wrap('<p itemscope="" itemtype="http://schema.org/ImageObject">'.$new_html.'</p>');
                        $value->replaceWith($new_html);
                        
                    }
                }
            }
        }
        
        $html = $html->html();
        $output = $html;
        return;
        break;
}
Внимание! Требует доработок под ваши настройки с шириной контента, ещё я добавил туда обёртку для fancybox, так же можете изменить на другую
    Александр Иванов
    01 мая 2020, 06:20
    0
    в кеш я не записываю, можете написать своё условие записи контента в кеш, сейчас работает на лету, но фотки кешируются, работает быстро
      Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
      2