You are here

function metatag_mobile_page_attachments_alter in Metatag 8

Implements hook_page_attachments_alter().

File

metatag_mobile/metatag_mobile.module, line 43
Contains metatag_mobile.module..

Code

function metatag_mobile_page_attachments_alter(array &$attachments) {
  if (isset($attachments['#attached']['html_head'])) {

    // A list of core tags that will be replaced, in the format:
    // core tag => Metatag-supplied tag
    // This assumes that the module's meta tags are output *before* the core
    // tags, if this changes then We're Going To Have A Bad Time.
    $dupes = [
      'MobileOptimized' => 'mobileoptimized',
      'HandheldFriendly' => 'handheldfriendly',
      'viewport' => 'viewport',
    ];

    // Keep track of when the Metatag-supplied meta tags are found, so if the
    // core tag is also found it can be removed.
    $found = [];
    foreach ($dupes as $core_tag => $meta_tag) {
      foreach ($attachments['#attached']['html_head'] as $key => $item) {
        if (isset($item[1])) {

          // The Metatag values are output before core's, so skip the first item
          // found so it can be picked up as the dupe; this is important for the
          // "viewport" meta tag where both core and Metatag use the same name.
          if ($item[1] == $meta_tag && !isset($found[$meta_tag])) {
            $found[$meta_tag] = $key;
          }
          elseif ($item[1] == $core_tag && isset($found[$meta_tag])) {

            // @todo This ought to work, but doesn't?
            // $attachments['#attached']['html_head'][$key]['#access'] = FALSE;
            unset($attachments['#attached']['html_head'][$key]);
          }
        }
      }
    }
  }
}