There's a hook for that. Here's my implementation.
<?php
function mymodule_some_page_callback() {
global $metatagOverrides;
// ... generate your page ...
$metatagOverrides = [
'og:image' => 'https://example.org/the-image.jpg',
'og:description' => 'Some description',
...
];
return $thePage;
}
function mymodule_metatag_metatags_view_alter(&$output, $instance, $options) {
if (!empty($metatagOverrides)) {
foreach ($metatagOverrides as $tagname => $value) {
if (array_key_exists($tagname, $output)) {
$output[$tagname]["#attached"]["drupal_add_html_head"][0][0]["#value"] = $value;
}
else {
$output[$tagname] = [
'#attached' => [
'drupal_add_html_head' => [
[
[
'#theme' => 'metatag_property',
'#tag' => 'meta',
'#id' => "{$tagname}_0",
'#name' => $tagname,
'#value' => $value,
'#weight' => 100,
],
"{$tagname}_0",
]
]
]
];
}
}
}