手动安装Open Graph标签


8

我正在尝试在我的网站上手动添加opengraph。我找到了该教程,它的工作原理很吸引人……但仅适用于Facebook。您可以在此处查看该教程:http://naileditdesign.com/facebook-open-graph-meta-tags-in-magento/。我希望它也可以在Pinterest上使用,但是它缺少一些关键方面,例如价格和货币标签。您知道我可以添加哪些代码行,以便它也可以在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 */ ?>

我知道我只缺少几行内容:价格和货币代码,如果有人可以帮助我,那就太好了。谢谢。

Answers:


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 /块/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/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>

应用程序/代码/本地/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
{
}

应用程序/代码/本地/ SE / Ogmeta /模型/系统/配置/后端/图像/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>

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; ?>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.