Автор Тема: Замена микроразметки data-vocabulary.org на schema.org  (Прочитано 2450 раз)

30 Январь 2020, 14:21:08
  • Пользователь
  • **
  • Сообщений: 92
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
Доброго времени суток.
Помогите пажалуйста исправить четыре предупреждения в Breadcrumb.
Во всех предупреждениях такой красный текст:
Google больше не поддерживает разметку data-vocabulary.org. Используйте разметку schema.org.

Путь к файлу
/www/themes/warehouse/breadcrumb1.tpl
Вот что записано в файле breadcrumb1.tpl
 

<!-- Breadcrumb -->
{if isset($smarty.capture.path)}{assign var='path' value=$smarty.capture.path}{/if}
<div class="breadcrumb"><div class="fixed_width">
   <div itemscope itemtype="data-vocabulary.org/Breadcrumb"> <a href="{$base_dir}" title="{l s='return to Home'}" itemprop="url"><span itemprop="title">{l s='Home'}</span></a></div>
   
   {if isset($path) AND $path}
      <span class="navigation-pipe" {if isset($category) && $category->id_category == 1}style="display:none;"{/if}>{$navigationPipe|escape:html:'UTF-8'}</span>
      {if !$path|strpos:'span'}
         <span class="navigation_page">{$path}</span>
      {else}
         {$path}
      {/if}
   {/if}</div>
</div>
<!-- /Breadcrumb -->
30 Январь 2020, 17:51:37
Ответ #1
  • Пользователь
  • **
  • Сообщений: 92
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
Сам отвечаю на свой вопрос может кому пригодится

Микроразметка Schema.org

Обновлено:
- display:none изменен на meta
- position теперь начинается с 1
- путь хлебных крошек для товара теперь привязан к категории по умолчанию

Примечание: Перед тем, как изменять хлебные крошки убедитесь, что вы назначили для каждого товара наиболее релевантную ему категорию по умолчанию. Желательно, чтобы это была категория последнего уровня вложенности, так как путь хлебных крошек будет составлен на основании этой категории.

1. В файле ваш_сайт/themes/ваша_тема/breadcrumb.tpl
Заменяем:

PHP:
<!-- Breadcrumb -->
{if isset($smarty.capture.path)}{assign var='path' value=$smarty.capture.path}{/if}
<div class="breadcrumb clearfix">
    <a class="home" href="{if isset($force_ssl) && $force_ssl}{$base_dir_ssl}{else}{$base_dir}{/if}" title="{l s='Return to Home'}"><i class="icon-home"></i></a>
    {if isset($path) AND $path}
        <span class="navigation-pipe"{if isset($category) && isset($category->id_category) && $category->id_category == (int)Configuration::get('PS_ROOT_CATEGORY')} style="display:none;"{/if}>{$navigationPipe|escape:'html':'UTF-8'}</span>
        {if $path|strpos:'span' !== false}
            <span class="navigation_page">{$path|@replace:'<a ': '<span itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" '|@replace:'data-gg="">': '><span itemprop="title">'|@replace:'</a>': '</span></a></span>'}</span>
        {else}
            {$path}
        {/if}
    {/if}
</div>


на:


PHP:
<!-- Breadcrumb -->
{if isset($smarty.capture.path)}{assign var='path' value=$smarty.capture.path}{/if}
<div class="breadcrumb" {if $page_name == 'product' or $page_name == 'category' or $page_name == 'cms'}itemscope itemtype="http://schema.org/BreadcrumbList"{/if}>
<!--    <div class="container"  > -->
        <!--<meta itemprop="name" content="{$meta_title|escape:'html':'UTF-8'}"/>-->
        <span {if $page_name == 'product' or $page_name == 'category' or $page_name == 'cms'}itemprop="itemListElement" itemscope="" itemtype="http://schema.org/ListItem"{/if}><meta itemprop="position" content="1"><a class="home" itemprop="item" href="{if isset($force_ssl) && $force_ssl}{$base_dir_ssl}{else}{$base_dir}{/if}" title="{l s='Return to Home'}"><meta itemprop="name" content="{l s='Home'}" /><i class="icon-home"></i></a></span>
    {if isset($path) AND $path}
        <span  class="navigation-pipe"  {if isset($category) && isset($category->id_category) && $category->id_category == (int)Configuration::get('PS_ROOT_CATEGORY')} style="display:none;"{/if}>{$navigationPipe|escape:'html':'UTF-8'}</span>
        {if $page_name == 'product' or $page_name == 'category' or $page_name == 'cms'}
            {if $path|strpos:'span' !== false}
                <span  class="navigation_page" >
                {$path|@replace:'<a ': '<span > <span >
                    <a itemprop="item" '|@replace:'data-gg="">': '>
                    <span >'|@replace:'</a>': '</a></span></span>'}</span>
            {else}
                <span itemprop="itemListElement" class="item-breadcrumb" itemscope="" itemtype="http://schema.org/ListItem"><meta itemprop="position" content="1"><meta itemprop="item" content="{if isset($force_ssl) && $force_ssl}https://{$smarty.server.HTTP_HOST}{$smarty.server.REQUEST_URI}{else}http://{$smarty.server.HTTP_HOST}{$smarty.server.REQUEST_URI}{/if}" /><meta itemprop="name" content="{$path}" /><span class="item-breadalone">{$path}</span></span>
            {/if}
        {else}
            {if $path|strpos:'span' !== false}
                <span  class="navigation_page" >
                {$path|@replace:'<a ': '<span > <span >
                    <a '|@replace:'data-gg="">': '>
                    <span >'|@replace:'</a>': '</a></span></span>'}</span>
            {else}
                <span class="item-breadalone">{$path}</span>
            {/if}
        {/if}
    {/if}
</div>

2. Создаем файл Tools.php в кодировке UTF-8 без BOM (можно сделать, например, с помощью Notepad++ ) с нижеследующим содержанием и закидываем его в папку ваш_сайт/override/classes/
PHP:


<?php

class Tools extends ToolsCore{
public static function getPath($id_category, $path = '', $link_on_the_item = false, $category_type = 'products', Context $context = null)
    {
        if (!$context)
            $context = Context::getContext();
        $id_category = (int)$id_category;
        if ($id_category == 1)
            return '<span class="navigation_end">'.$path.'</span>';
        $pipe = Configuration::get('PS_NAVIGATION_PIPE');
        if (empty($pipe))
            $pipe = '>';
        $full_path = '';
        if ($category_type === 'products')
        {
            $interval = Category::getInterval($id_category);
            $id_root_category = $context->shop->getCategory();
            $interval_root = Category::getInterval($id_root_category);
            if ($interval)
            {
                $sql = 'SELECT c.id_category, cl.name, cl.link_rewrite, cl.meta_title
                        FROM '._DB_PREFIX_.'category c
                        LEFT JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = c.id_category'.Shop::addSqlRestrictionOnLang('cl').')
                        '.Shop::addSqlAssociation('category', 'c').'
                        WHERE c.nleft <= '.$interval['nleft'].'
                            AND c.nright >= '.$interval['nright'].'
                            AND c.nleft >= '.$interval_root['nleft'].'
                            AND c.nright <= '.$interval_root['nright'].'
                            AND cl.id_lang = '.(int)$context->language->id.'
                            AND c.active = 1
                            AND c.level_depth > '.(int)$interval_root['level_depth'].'
                        ORDER BY c.level_depth ASC';
                $categories = Db::getInstance()->executeS($sql);
                $n = 1;
                $n_categories = count($categories);
                foreach ($categories as $key => $category)
                {
                    $key = $key+2;
                    $full_path .='<span itemprop="itemListElement" class="item-breadcrumb" itemscope="" itemtype="http://schema.org/ListItem" ><meta itemprop="position" content="'.$key.'">'. (($n < $n_categories || $link_on_the_item) ? '<a itemprop="url" href="'.Tools::safeOutput($context->link->getCategoryLink((int)$category['id_category'], $category['link_rewrite'])).'" title="'.htmlentities($category['name'], ENT_NOQUOTES, 'UTF-8').'">' : '<meta itemprop="url" content="'.Tools::safeOutput($context->link->getCategoryLink((int)$category['id_category'], $category['link_rewrite'])).'" title="'.htmlentities($category['name'], ENT_NOQUOTES, 'UTF-8').'" />').'<meta itemprop="name" content="'.htmlentities($category['name'], ENT_NOQUOTES, 'UTF-8').'" />'.
                    htmlentities($category['name'], ENT_NOQUOTES, 'UTF-8').
                    (($n < $n_categories || $link_on_the_item) ? '</a>' : '').
                    (($n++ != $n_categories || !empty($path)) ? '<span class="navigation-pipe">'.$pipe.'</span>' : '').'</span>';
                }
                return $full_path.$path;
            }
        }
        else if ($category_type === 'CMS')
        {
            $category = new CMSCategory($id_category, $context->language->id);
            if (!Validate::isLoadedObject($category))
                die(Tools::displayError());
            $category_link = $context->link->getCMSCategoryLink($category);
            if ($path != $category->name)
                $full_path .= '<a href="'.Tools::safeOutput($category_link).'">'.htmlentities($category->name, ENT_NOQUOTES, 'UTF-8').'</a><span class="navigation-pipe">'.$pipe.'</span>'.$path;
            else
                $full_path = ($link_on_the_item ? '<a href="'.Tools::safeOutput($category_link).'">' : '').htmlentities($path, ENT_NOQUOTES, 'UTF-8').($link_on_the_item ? '</a>' : '');
            return Tools::getPath($category->id_parent, $full_path, $link_on_the_item, $category_type);
        }
    }
}

3. Создаем файл ProductController.php в кодировке UTF-8 без BOM с нижеследующим содержанием и закидываем его в папку ваш_сайт/override/controllers/front/
PHP:


<?php

class ProductController extends ProductControllerCore
{

    protected function assignCategory()
    {
        // Assign category to the template
        if ($this->category !== false && Validate::isLoadedObject($this->category) && $this->category->inShop() && $this->category->isAssociatedToShop()) {
            $this->category = new Category((int)$this->product->id_category_default, (int)$this->context->language->id);
            $path = Tools::getPath($this->product->id_category_default, $this->product->name, true);
        } elseif (Category::inShopStatic($this->product->id_category_default, $this->context->shop)) {
            $this->category = new Category((int)$this->product->id_category_default, (int)$this->context->language->id);
            if (Validate::isLoadedObject($this->category) && $this->category->active && $this->category->isAssociatedToShop()) {
                $path = Tools::getPath((int)$this->product->id_category_default, $this->product->name);
            }
        }
        if (!isset($path) || !$path) {
            $this->category = new Category((int)$this->product->id_category_default, (int)$this->context->language->id);
            $path = Tools::getPath($this->product->id_category_default, $this->product->name, true);
        }

        $sub_categories = array();
        if (Validate::isLoadedObject($this->category)) {
            $sub_categories = $this->category->getSubCategories($this->context->language->id, true);

            // various assignements before Hook::exec
            $this->context->smarty->assign(array(
                'path' => $path,
                'category' => $this->category,
                'subCategories' => $sub_categories,
                'id_category_current' => (int)$this->category->id,
                'id_category_parent' => (int)$this->category->id_parent,
                'return_category_name' => Tools::safeOutput($this->category->getFieldByLang('name')),
                'categories' => Category::getHomeCategories($this->context->language->id, true, (int)$this->context->shop->id)
            ));
        }
        $this->context->smarty->assign(array('HOOK_PRODUCT_FOOTER' => Hook::exec('displayFooterProduct', array('product' => $this->product, 'category' => $this->category))));
    }

}

4. Удаляем файл class_index.php из папки ваш_сайт/cache, и на всякий случай чистим кэш в "Расширенные параметры > Производительность".


Тема на форуме Prestashop:
https://www.prestashop.com/forums/t...adcrumb-schemaorg-microdate-for-prestashop-16