Create custom meta tags in Drupal 8

By Arun AK, 6 November, 2019

In Drupal 8 we can use the Metatag module to add metatag to the pages. This module supports almost all the meta tags. Also, in case if you could not find a required meta tag in this module, it is easy to create a new meta tag by extending the 'MetaNameBase' class provided by the Metatag module.

Metatags are defined as a plugin in the Drupal 8 Metatag module. Hence to create a new metatag, create a new custom plugin using a custom module. For that, create a Plugin directory in your custom module.


Then inside 'Tag' directory, create your plugin class file. Eg: CustomMetatag.php

Then define your custom metag tag as below:


namespace Drupal\mymodule\Plugin\metatag\Tag;

use Drupal\metatag\Plugin\metatag\Tag\MetaNameBase;

 * Provides a plugin for the 'custom-metatag' meta tag.
 * @MetatagTag(
 *   id = "custom-metatag",
 *   label = @Translation("Custom Metatag"),
 *   description = @Translation("This is a custom meta tag."),
 *   name = "custom_metatag",
 *   group = "advanced",
 *   weight = 5,
 *   type = "label",
 *   secure = FALSE,
 *   multiple = FALSE
 * )

class CustomMetatag extends MetaNameBase {
  // Nothing here yet. Just a placeholder class for a plugin.

Then clear the Drupal cache. Now you can see the new Custom Meta tag under the Advanced tags section on the content edit page.

Custom Metatag

Once you fill the value for the metatag, your custom metatag will render in the pages like below.

Custom Metatag Display