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
1 2 3 4 5 6 7 8 9 10 |
<?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
1 2 3 4 5 6 7 8 9 |
<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!
You may, however, post doubts in the comments section and I’d be happy to solve them!
Flash 5 stars if you liked my post ?
Thank You!
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 businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Set Cron in Magento 2
How to Enable Ajax Newsletter in Magento 2
Next