How to Override Product View Page Social Meta Tags in Magento 2

Social Meta Tags allows store admin to control how the pages appear on social media. SEO best practice says to have unique social meta tags for each product page or category pages in Magento 2 store. Default Magento 2 provides social meta tags for the product pages, but sometimes a store owner may want to hide social meta tags or change the title, image or any other social meta tag content dynamically. In cases, you need to override product view page social meta tags in Magento 2.

Implementation to override product view page social meta tags in Magento 2:

Create catalog_product_opengraph.xml file at Vendor\Extension\view\frontend\layout

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="opengraph.general">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Vendor_Extension::general.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Create general.phtml file at Vendor\Extension\view\frontend\templates

<meta property="og:type" content="product" />
<meta property="og:title" content="<?= $block->escapeHtmlAttr($block->stripTags($block->getProduct()->getName())) ?>" />
<meta property="og:image" content="<?= $block->escapeUrl($block->getImage($block->getProduct(), 'product_base_image')->getImageUrl()) ?>" />
<meta property="og:description" content="<?= $block->escapeHtmlAttr($block->stripTags($block->getProduct()->getShortDescription())) ?>" />
<meta property="og:url" content="<?= $block->escapeUrl($block->getProduct()->getProductUrl()) ?>" />
<?php if ($priceAmount = $block->getProduct()->getFinalPrice()):?>
    <meta property="product:price:amount" content="<?= /* @escapeNotVerified */ $priceAmount ?>"/>
    <?= $block->getChildHtml('meta.currency') ?>
<?php endif;?>

A quick solution to dynamically override social meta tags for Magento 2 product pages!

Thank You!

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...