Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
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'];

            }
        }
    }
}

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon