How to Add Meta Tags to Header in Magento 2
As you might already know, the HTML
<head> section of the page includes different meta tags, CSS, JS files definition, JS code’s pieces, etc. Normally, no complex logic is needed to add some proper content there. However, in various situations, we will need to insert several elements which depend on the configuration of the system into the head section.
If you have been working with Magento 1, you will find out that it’s easy to operate with the contents of the head section. However, in the newest Magento version, adding meta tags to header might be a bit tricky for you. Because of that, in today post, I will guide you on how to add blocks and templates, more specifically how to Add Meta Tags to the head section in Magento 2.
Add Meta Tags to Header
In order to add
<meta> tags to your layout’s
<head> element, you need to create a theme extending file which is similar to this:
\Magento\Framework\View\Page\Config\Renderer is the class which the
<meta> tags is rendered by. There are five types of meta, and a catch-all (the default) are rendered by this class:
- “default” case
You can use the following as an examples to include in your layout themes:
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> <!-- This will create a tag like '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">' --> <meta name="x_ua_compatible" content="IE=edge,chrome=1"/> <!-- This will create a tag like '<meta property="og:type" content="article"/>'' --> <meta name="og:type" content="article"/> <!-- This will create a tag like '<meta charset="UTF-8">' --> <meta name="charset" content="UTF-8"/> <!-- This will create a tag like '<meta http-equiv="Content-Type" content="content-type-value"/>' --> <meta name="content_type" content="content-type-value"/> <!-- This tag will not render (see \Magento\Framework\View\Page\Config\Renderer for details) --> <meta name="media_type" content="any-value"/> <!-- This will create a tag like '<meta name="my_custom_type" content="my_custom_value"/>' --> <meta name="my_custom_type" content="my_custom_value"/> </head> </page>
Above I have just provided you the method to add meta tags to header in Magento 2. I hope it is helpful for you. Should you have any questions or new ideas, feel free to leave a comment below.
Enjoyed the tutorial? Spread it to your friends!