Установить тег Open Graph вручную


8

Я пытаюсь добавить opengraph на моем сайте вручную. Я нашел учебник, и он работает как шарм ... но только для Facebook. Вы можете просмотреть учебник здесь: http://naileditdesign.com/facebook-open-graph-meta-tags-in-magento/. Я хочу, чтобы он работал и в Pinterest, но в нем отсутствует какой-то ключевой аспект, такой как тег Цена и валюта. Знаете ли вы, какие строки кода я могу добавить, чтобы он также работал на интерес, а не только на Facebook.

<?php /* Open Graph Protocol for Facebook and SEO START */ ?>
<?php if(Mage::registry('current_product')): ?>
 <?php $product = Mage::registry('current_product'); ?>
 <meta property="og:title" content="<?php echo ($product->getName()); ?>" />
 <meta property="og:type" content="product" />
 <meta property="og:image" content="<?php echo $this->helper('catalog/image')->init($product, 'small_image')->resize(200,200);?>" />
 <meta property="og:url" content="<?php echo Mage::registry('product')->getProductUrl(); ?>" />
 <meta property="og:description" content="<?php echo strip_tags(($product->getShortDescription())); ?>" />
 <meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName(); ?>" />
<?php elseif(Mage::registry('current_category')): ?>
 <meta property="og:title" content="<?php echo $this->getTitle() ?>" />
 <meta property="og:type" content="product.group" />
 <meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl();?>" />
 <meta property="og:description" content="<?php echo strip_tags($this->getDescription()) ?>" />
 <meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName(); ?>" />
<?php elseif((Mage::getSingleton('cms/page')->getIdentifier() == 'home' &&
 Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms')) : ?>
 <meta property="og:title" content="<?php echo $this->getTitle() ?>" />
 <meta property="og:type" content="website" />
 <meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl();?>" />
 <meta property="og:description" content="<?php echo strip_tags($this->getDescription()) ?>" />
 <meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName(); ?>" />
<?php else: ?>
 <meta property="og:title" content="<?php echo $this->getTitle() ?>" />
 <meta property="og:type" content="article" />
 <meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl();?>" />
 <meta property="og:description" content="<?php echo strip_tags($this->getDescription()) ?>" />
 <meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName(); ?>" />
<?php endif; ?>
<?php /* Open Graph Protocol for Facebook and SEO END */ ?>

Я знаю, что мне не хватает только пары строк: цена и код валюты. Если какое-то тело поможет мне, это было бы здорово. Спасибо.

Ответы:


6

Это должно работать:

<meta property="og:price:amount" content="<?php echo Mage::registry('product')->getFinalPrice() ?>" />
<meta property="og:price:currency" content="<?php echo Mage::app()->getStore()->getCurrentCurrencyCode(); ?>" />

5

Этот (на основе @Justin) исправляет отсутствующие по умолчанию заголовок и описание домашней страницы, сначала создайте /magento/app/design/frontend/mysite/mytheme/template/custom/og_meta.phtml :

<?php
$og = [
    'title' => $this->getLayout()->getBlock('head')->getTitle(),
    'site_name' => Mage::app()->getStore()->getName(),
    'description' => trim(strip_tags($this->getLayout()->getBlock('head')->getDescription())),
    'url' => $this->helper('core/url')->getCurrentUrl(),
];

if(Mage::registry('current_product')):
    $product = Mage::registry('current_product');
    $og['title'] = $product->getName();
    $og['type'] = 'product';
    $og['image'] = $this->helper('catalog/image')->init($product, 'image');    
    $og['description'] = strip_tags(($product->getShortDescription()));
    $og['price:amount'] = Mage::registry('product')->getFinalPrice();
    $og['price:currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
elseif(Mage::registry('current_category')):
    $og['type'] = 'product.group';        
elseif((Mage::getSingleton('cms/page')->getIdentifier() == 'home' &&
    Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms')) :
    $og['type'] = 'website';
else:
    $og['type'] = 'article';
endif;
?>
<?php foreach($og as $key => $value): ?>
<meta property="og:<?php echo $key ?>" content="<?php echo $value ?>">
<?php endforeach; ?>

Затем добавьте, например, в /magento/app/design/frontend/mysite/mytheme/layout/page.xml:

<block type="page/html_head" name="head" as="head">
    ...

    <block type="core/template" name="ogmeta" template="custom/og_meta.phtml" />

    ...
</block>

Для того, чтобы придать этот фрагмент в голову блока шаблона. Наслаждайтесь!


3

Вот исправленная версия вашего примера кода с добавленной информацией о цене продукта.

<?    
$og = [];
$og['title'] = $this->getTitle();
$og['site_name'] = Mage::app()->getStore()->getName();
$og['description'] = strip_tags($this->getDescription());
$og['url'] = $this->helper('core/url')->getCurrentUrl();

if(Mage::registry('current_product')):
    $product = Mage::registry('current_product');
    $og['title'] = $product->getName();
    $og['type'] = 'product';
    $og['image'] = $this->helper('catalog/image')->init($product, 'image');    
    $og['description'] = strip_tags(($product->getShortDescription()));
    $og['price:amount'] = Mage::registry('product')->getFinalPrice();
    $og['price:currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
elseif(Mage::registry('current_category')):
    $og['type'] = 'product.group';        
elseif((Mage::getSingleton('cms/page')->getIdentifier() == 'home' &&
    Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms')) :
    $og['type'] = 'website';
else:
    $og['type'] = 'article';
endif;
?>
<? foreach($og as $key => $value): ?>
<meta property="og:<?= $key ?>" content="<?= $value ?>">
<? endforeach; ?>

3

Вместо того, чтобы вручную добавлять код в head.phtml, вы можете сделать это в модуле, который намного чище и гибче.

Приложение / код / ​​местные / SE / Ogmeta / Block / Html / Head.php

<?php
/**
 * Class StackExchange_Ogmeta_Block_Html_Head
 */
class SE_Ogmeta_Block_Html_Head extends Mage_Page_Block_Html_Head
{
    public function _construct()
    {
        $this->setTemplate('se_og_meta/meta.phtml');
    }

    protected function _prepareLayout()
    {
        try {
            $baseUrl          = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
            $storeId          = $this->helper('core')->getStoreId();
            $coreStringHelper = Mage::helper('core/string');

            if ($currentProduct = Mage::registry('current_product')) {
                $title              = $currentProduct->getMetaTitle();
                $description        = $currentProduct->getMetaDescription();
                $productName        = $currentProduct->getName();
                $amount             = $currentProduct->getFinalPrice();
                $productDescription = $currentProduct->getDescription();
                $productImages      = $currentProduct->getMediaGalleryImages();
                $currency           = Mage::app()->getStore()->getCurrentCurrencyCode();

                if ($title) {
                    $this->setOgTitle($title);
                } else {
                    $this->setOgTitle($coreStringHelper->substr($productName, 0, 255));
                }

                if ($description) {
                    $this->setOgDescription($description);
                } else {
                    $this->setOgDescription(
                        $coreStringHelper->substr(
                            $coreStringHelper->stripTags($productDescription), 0, 255
                        )
                    );
                }

                foreach ($productImages->getItems() as $image) {
                    $images[] = $baseUrl . 'catalog/product' . $image->getFile();
                }

                if ($images) {
                    $this->setImages($images);
                }

                if ($amount) {
                    $this->setOgAmount($amount);
                }

                if ($currency) {
                    $this->setOgCurrency($currency);
                }
            } elseif ($currentCategory = Mage::registry('current_category')) {
                $title                   = $currentCategory->getMetaTitle();
                $categoryName            = $currentCategory->getName();
                $categoryMetaDescription = $currentCategory->getMetaDescription();
                $categoryDescription     = $currentCategory->getDescription()
                $categoryThumbnail       = $currentCategory->getThumbnail();

                if ($title) {
                    $this->setOgTitle($title);
                } else {
                    $this->setOgTitle($coreStringHelper->substr($categoryName, 0, 255));
                }

                if ($categoryMetaDescription) {
                    $this->setOgDescription($categoryMetaDescription);
                } else {
                    $this->setOgDescription($coreStringHelper->substr($coreStringHelper->stripTags($categoryDescription)), 0, 255));
                }

                if ($categoryThumbnail) {
                    $this->setImages([$baseUrl . 'catalog/category/' . $image]);
                }
            }

            $this->setCurrentUrl($this->helper('core/url')->getCurrentUrl());

            $title = $this->getOgTitle();

            if (!$title) {
                $this->setOgTitle(Mage::getStoreConfig('design/og_meta_head/og_default_title', $storeId));
            }

            $description = $this->getOgDescription();

            if (!$description) {
                $this->setOgDescription(Mage::getStoreConfig('design/og_meta_head/og_default_description', $storeId));
            }

            $images = $this->getImages();

            if (!$images) {
                $this->setImages([$baseUrl . 'ogmeta/' . Mage::getStoreConfig('design/og_meta_head/og_default_image', $storeId)]);
            }
        } catch (Exception $e) {
            Mage::log($e->getMessage());
        }
    }
}

Приложение / код / ​​местные / SE / Ogmeta / и т.д. / config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <SE_Ogmeta>
            <version>0.1.0</version>
        </SE_Ogmeta>
    </modules>
    <global>
        <blocks>
            <se_ogmeta>
                <class>SE_Ogmeta_Block</class>
            </se_ogmeta>
        </blocks>
        <helpers>
            <se_ogmeta>
                <class>SE_Ogmeta_Helper</class>
            </se_ogmeta>
        </helpers>
        <models>
            <se_ogmeta>
                <class>SE_Ogmeta_Model</class>
            </se_ogmeta>
        </models>
    </global>
    <frontend>
        <layout>
            <updates>
                <se_ogmeta>
                    <file>se_og_meta.xml</file>
                </se_ogmeta>
            </updates>
        </layout>
    </frontend>
</config>

Приложение / код / ​​местные / SE / Ogmeta / и т.д. / System.Xml

<config>
    <sections>
        <design translate="label">
            <groups>
                <og_meta_head translate="label" module="se_ogmeta">
                    <label>OG Meta Head</label>
                    <frontend_type>text</frontend_type>
                    <sort_order>30</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
                        <og_default_image translate="label comment">
                            <label>OG Meta Default Image</label>
                            <comment>Allowed file types: PNG, GIF, JPG, JPEG. Not all browsers support all these formats!</comment>
                            <frontend_type>image</frontend_type>
                            <backend_model>se_ogmeta/system_config_backend_image_metaimage</backend_model>
                            <base_url type="media" scope_info="1">ogmeta</base_url>
                            <sort_order>5</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </og_default_image>
                        <og_default_title translate="label">
                            <label>OG Meta Default Title</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </og_default_title>
                        <og_default_description translate="label">
                            <label>OG Meta Default Description</label>
                            <frontend_type>textarea</frontend_type>
                            <sort_order>20</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </og_default_description>
                    </fields>
                </og_meta_head>
            </groups>
        </design>
    </sections>
</config>

HTDOCS / приложение / код / ​​местные / SE / Ogmeta / Helper / Data.php

<?php
class SE_Ogmeta_Helper_Data extends Mage_Core_Helper_Data
{
}

Приложение / код / ​​местные / SE / Ogmeta / модель / System / Config / Backend / Image / Metaimage.php

/**
 * System config image field backend model for Zend PDF generator
 */
class SE_Ogmeta_Model_System_Config_Backend_Image_Metaimage extends Mage_Adminhtml_Model_System_Config_Backend_Image
{
    /**
     * The tail part of directory path for uploading
     */
    const UPLOAD_DIR = 'ogmeta';

    /**
     * Token for the root part of directory path for uploading
     */
    const UPLOAD_ROOT = 'media';

    /**
     * Return path to directory for upload file
     * @return string
     * @throw Mage_Core_Exception
     */
    protected function _getUploadDir()
    {
        $uploadDir  = $this->_appendScopeInfo(self::UPLOAD_DIR);
        $uploadRoot = $this->_getUploadRoot(self::UPLOAD_ROOT);
        $uploadDir  = $uploadRoot . '/' . $uploadDir;
        return $uploadDir;
    }

    /**
     * Makes a decision about whether to add info about the scope.
     * @return boolean
     */
    protected function _addWhetherScopeInfo()
    {
        return true;
    }

    /**
     * Getter for allowed extensions of uploaded files.
     * @return array
     */
    protected function _getAllowedExtensions()
    {
        return ['png', 'gif', 'jpg', 'jpeg', 'apng', 'svg'];
    }

    /**
     * Get real media dir path
     * @param  $token
     * @return string
     */
    protected function _getUploadRoot($token)
    {
        return Mage::getBaseDir($token);
    }
}

приложение / дизайн / интерфейс / базы / по умолчанию / макет / se_og_meta.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
        <reference name="head">
            <block type="se_ogmeta/html_head" name="ogmeta" />
        </reference>
    </default>
</layout>

приложение / дизайн / интерфейс / базы / по умолчанию / шаблон / se_og_meta / meta.phtml

<?php
/**
 * Template for SE_Ogmeta_Head
 */
?>
<meta name="og:title" content="<?php echo $this->escapeHtml($this->getOgTitle()) ?>"/>
<meta name="og:url" content="<?php echo $this->escapeHtml($this->getCurrentUrl()) ?>"/>
<meta name="og:type" content="website"/>
<?php if (count($this->getImages()) > 0) : ?>
    <?php foreach ($this->getImages() as $image) : ?>
        <meta name="og:image" content="<?php echo $this->escapeHtml($image) ?>"/>
    <?php endforeach; ?>
<?php endif; ?>
<meta name="og:description" content="<?php echo $this->escapeHtml($this->getOgDescription()) ?>"/>
<?php if ($this->getOgAmount() && $this->getOgCurrency()): ?>
<meta property="og:price:amount" content="<?php echo $this->escapeHtml($this->getOgAmount()) ?>" />
<meta property="og:price:currency" content="<?php echo $this->escapeHtml($this->getOgCurrency()) ?>" />
<?php endif; ?>

приложение / и т.д. / модули / SE_Ogmeta.xml

<?xml version="1.0"?>
<config>
    <modules>
        <SE_Ogmeta>
            <active>true</active>
            <codePool>local</codePool>
        </SE_Ogmeta>
    </modules>
</config>

0

Код обновлен с учетом последних требований Facebook.

<?php
$og = [
    'title' => $this->getLayout()->getBlock('head')->getTitle(),
    'site_name' => Mage::app()->getStore()->getName(),
    'description' => trim(strip_tags($this->getLayout()->getBlock('head')->getDescription())),
    'url' => $this->helper('core/url')->getCurrentUrl(),
];
$ogp = [];

if(Mage::registry('current_product')):
    $product = Mage::registry('current_product');
    $og['title'] = $product->getName();
    $og['type'] = 'product.item';
    $og['image'] = $this->helper('catalog/image')->init($product, 'image');    
    $og['description'] = strip_tags(($product->getShortDescription()));
    $ogp['product:retailer_item_id'] = Mage::registry('product')->getSku();
    $ogp['product:price:amount'] = Mage::registry('product')->getFinalPrice();
    $ogp['product:price:currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
    $ogp['product:availability'] = 'in stock';
    $ogp['product:condition'] = 'new';
elseif(Mage::registry('current_category')):
    $category = Mage::registry('current_category');
    $og['image'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/category/'.$category->getThumbnail(); 
    $og['type'] = 'product.group';
elseif((Mage::getSingleton('cms/page')->getIdentifier() == 'home' &&
    Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms')) :
    $og['type'] = 'website';
else:
    $og['type'] = 'article';
endif;
?>

<meta property="fb:app_id" content="APP_ID" />
<?php foreach($og as $key => $value): ?>
<meta property="og:<?php echo $key ?>" content="<?php echo $value ?>">
<?php endforeach; ?>
<?php if(!empty($ogp)): ?>
<?php foreach($ogp as $key => $value): ?>
<meta property="<?php echo $key ?>" content="<?php echo $value ?>">
<?php endforeach; ?>
<?php endif; ?>
Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.