How to add open graph meta tags programmatically in Drupal 8 & 9

function THEMENAME_page_attachments_alter(array &$page)
{
    $route = \Drupal::routeMatch()->getRouteObject();
    if ($route) {
        $view_id = $route->getDefault('view_id');
        if (!empty($view_id)) {

            if ($view_id == 'devoirs') {
                $img_url = "path/to/image";

                $og_image = array(
                    '#tag' => 'meta',
                    '#attributes' => array(
                        'property' => 'og:image',
                        'content' => $img_url,
                    ),
                );
                $page['#attached']['html_head'][] = [$og_image, 'og_image'];


                $og_description = array(
                    '#tag' => 'meta',
                    '#attributes' => array(
                        "property" => "og:description",
                        "content" => t("Lorem ipsum"),
                    ),
                );
                $page['#attached']['html_head'][] = [$og_description, 'og:description'];

            }
        }
    }
}

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...