Skip to main content
Category:

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

 

Code snippet that can be used  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'];

            }
        }
    }
}

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook