Member-only story
How to Alter a Metatag in Drupal
Change its value easily using this hook
Metatags are used to describe a page’s content. Drupal has a module that let you manage them easily: https://www.drupal.org/project/metatag
Ideally, you should always try to configure them using the admin page of the module. In case you can’t find a proper token to use, you can also create your own and use it in metatag module.
What I’m going to explain is how to alter an existing metatag. This might be useful to you in cases where you need to implement some logic and you don’t want to create a token for it.
For the example below, I’m editing the metatag “twitter_cards_title”. Make sure you add a condition the check the name, otherwise you’ll apply your changes to other metatags as well.
I have a content type “thank_you_page” that has an entity reference field that loads nodes of type “campaign”.
The code is checking whether field_tweet_text is empty on the parent node (campaign). If it isn’t, that value is used for the metatag, if it is, then node title is used as value.
You can find more information about this hook here. If you have any question, feel free to leave a comment.
/**
* Implements hook_page_attachments_alter().
* @param array…