Instalar manualmente Open Graph Tag

8

Estoy tratando de agregar Opengraph en mi sitio web manualmente. Encontré el tutorial y funciona de maravilla ... pero solo para Facebook. Puede ver el tutorial aquí: http://naileditdesign.com/facebook-open-graph-meta-tags-in-magento/. También quiero que funcione en Pinterest, pero le faltan algunos aspectos clave, como la etiqueta de precio y moneda. ¿Sabes qué líneas de código puedo agregar para que también funcione en el pinterest, en lugar de solo en 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 */ ?>

Sé que solo me faltan un par de líneas: precio y código de moneda, si algún organismo me puede ayudar, sería genial. Gracias.

Nabeel M
fuente

Respuestas:

6

Estos deberían funcionar:

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

Este (basado en @Justin) corrige el título y la descripción que faltan por defecto para la página de inicio, primero cree /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; ?>

A continuación, agregue, por ejemplo, a /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>

Para inyectar este fragmento en el bloque de plantilla de cabecera . ¡Disfrutar!

matinfo
fuente
3

Aquí hay una versión limpia de su código de ejemplo con la información del precio del producto agregada también.

<?    
$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; ?>
Justin
fuente
3

En lugar de agregar manualmente el código en head.phtml, puede hacerlo en un módulo que sea mucho más limpio y flexible.

aplicación / código / local / 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());
        }
    }
}

aplicación / código / local / SE / Ogmeta / etc / 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>

app / code / local / SE / Ogmeta / etc / 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 / app / code / local / SE / Ogmeta / Helper / Data.php

<?php
class SE_Ogmeta_Helper_Data extends Mage_Core_Helper_Data
{
}

app / code / local / SE / Ogmeta / Model / 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);
    }
}

app / design / frontend / base / default / layout / 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>

app / design / frontend / base / default / template / 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; ?>

app / etc / modules / SE_Ogmeta.xml

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

Código actualizado a los últimos requisitos de 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; ?>
Mgt-Wizards
fuente