-
-
Save thejimbirch/fe880c406cfc3cf9854fa0511666fbc2 to your computer and use it in GitHub Desktop.
OR statements in metatags...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implements hook_metatags_attachments_alter(). | |
* | |
* This function allows you to define fallback tokens in case a field is empty. | |
* | |
* If all fallback values are empty, the tag will be empty. | |
* | |
* Example: [node:field_image:medium]||[node:field_legacy_image:medium]||/fallback.png | |
*/ | |
function example_metatags_attachments_alter(array &$metatag_attachments) { | |
if (!empty($metatag_attachments['#attached']['html_head'])) { | |
$url = \Drupal::request()->getSchemeAndHttpHost(); | |
$insecure_url = str_replace('https://', 'http://', $url); | |
foreach ($metatag_attachments['#attached']['html_head'] as &$attachment) { | |
if (isset($attachment[0]['#attributes']['content'])) { | |
$value = &$attachment[0]['#attributes']['content']; | |
} | |
elseif (isset($attachment[0]['#attributes']['href'])) { | |
$value = &$attachment[0]['#attributes']['href']; | |
} | |
if (isset($value) && strpos($value, '||') !== FALSE) { | |
$new_value = FALSE; | |
foreach (explode('||', $value) as $option) { | |
// We have to check against the URL because metatag will prepend our | |
// special tag value with the site URL if the tag plugin uses | |
// absolute URLs. | |
if (!empty($option) && $option !== $url && $option !== $insecure_url) { | |
// Make relative URLs absolute. | |
if (strpos($option, '/') === 0) { | |
$option = rtrim($url, '/') . $option; | |
} | |
$new_value = trim($option); | |
break; | |
} | |
} | |
$value = $new_value ?: ''; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment