Helpful functions and solutions
These are some helpful functions and solutions to issues i've encountered while developing.
Add Metatags
Add specific metatags to a page, for example, if you want to add a specific image to a page, you can use the following function, this function should be placed in the .module file.
function MODULE_NAME_page_attachments_alter(array &$page)
{
$meta_title = "";
$meta_description = "";
$meta_og_img = \Drupal::request()->getSchemeAndHttpHost() . '/themes/bootstrap/image.png';
$meta_title_html = [
'#type' => 'html_tag',
'#tag' => 'title',
'#value' => $meta_title
];
$meta_description = [
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => [
'name' => 'description',
'content' => $meta_description,
],
];
$meta_og_title = [
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => [
'name' => 'og:title',
'content' => $meta_title,
],
];
$meta_og_img_html = [
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => [
'name' => 'og:image',
'content' => $meta_og_img,
],
];
$tw_card = [
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => [
'name' => 'twitter:card',
'content' => 'summary_large_image',
],
];
$tw_title = [
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => [
'name' => 'twitter:title',
'content' => $meta_title,
],
];
$tw_image = [
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => [
'name' => 'twitter:image',
'content' => $meta_og_img,
],
];
$page['#attached']['html_head'][] = [$meta_title_html, 'title'];
$page['#attached']['html_head'][] = [$meta_description, 'description'];
$page['#attached']['html_head'][] = [$meta_og_title, 'og:title'];
$page['#attached']['html_head'][] = [$meta_og_img_html, 'og:image'];
$page['#attached']['html_head'][] = [$tw_card, 'twitter:card'];
$page['#attached']['html_head'][] = [$tw_title, 'twitter:title'];
$page['#attached']['html_head'][] = [$tw_image, 'twitter:image'];
}Create Next/Previous Post links
Create next and previous post links, this function should be placed in the .theme file or .module file.
Create Permalink without accents
Check if string Starts With
Group Array by Date
Flatten Array
Last updated