I need to add 'class' and 'data-type' attributes to meta tag containing description attribute. I was able to locate the core Metatag module, however I'm unable to find any documentation on how to customize output without altering the core.
1 Answer
function [your-theme]_page_attachments_alter(array &$attachments) {
$attachments = SwiftypeMetaDescription::add($attachments);
}
class SwiftypeMetaDescription{
/**
* @param array $attachments
* @return array
*/
public static function add(array $attachments): array
{
// check if $attachments contain html_head
if (empty($attachments['#attached']['html_head'])) {
return $attachments;
}
// loop through HTML head
foreach ($attachments['#attached']['html_head'] as $key => $attachment) {
// check if element name is defined
if (empty($attachment[1])) {
// if it's not, skip element
continue;
}
// if the element name equals 'description'
if ($attachment[1] == 'description') {
// add 'class' attribute
$attachments['#attached']['html_head'][$key][0]['#attributes']['class'] = 'swiftype';
// add 'data-type' attribute
$attachments['#attached']['html_head'][$key][0]['#attributes']['data-type'] = 'string';
}
}
return $attachments;
}
}