Last active
October 19, 2018 17:10
-
-
Save DanLaufer/4dc061a636995fd086d2325676d9ed19 to your computer and use it in GitHub Desktop.
Drupal 8 - Truncate <title> and <meta title> before suffix
This file contains hidden or 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
function mytheme_preprocess_html(&$variables) { | |
// truncate <title> to 58 characters, including the brand | |
$title_length = strlen($variables['head_title']['title']); | |
$ti_str_limit = 58; | |
$title_suffix = ' | My Company, LLC.'; | |
$suffix_length = strlen($title_suffix); | |
$allowable_length = $ti_str_limit - $suffix_length; | |
$allowable_length_w_ellipse = $allowable_length - 3; | |
if (strpos($variables['head_title']['title'], $title_suffix) == false) { | |
$variables['head_title']['title'] = $title_length > $allowable_length ? substr($variables['head_title']['title'], 0, $allowable_length_w_ellipse) . '...' : $variables['head_title']['title']; | |
$variables['head_title']['title'] .= $title_suffix; | |
} | |
} | |
function mytheme_page_attachments_alter(array &$attachments) { | |
foreach($attachments['#attached']['html_head'] as &$head_item) { | |
switch ($head_item[1]) { | |
case 'title': | |
// truncate title metatag to 58 characters, including the brand | |
$title_length = strlen($head_item[0]['#attributes']['content']); | |
$ti_str_limit = 58; | |
$title_suffix = ' | My Company, LLC.'; | |
$suffix_length = strlen($title_suffix); | |
$allowable_length = $ti_str_limit - $suffix_length; | |
$allowable_length_w_ellipse = $allowable_length - 3; | |
if (strpos($head_item[0]['#attributes']['content'], $title_suffix) == false) { | |
$head_item[0]['#attributes']['content'] = $title_length > $allowable_length ? substr($head_item[0]['#attributes']['content'], 0, $allowable_length_w_ellipse) . '...' : $head_item[0]['#attributes']['content']; | |
$head_item[0]['#attributes']['content'] .= $title_suffix; | |
} | |
break; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment