Change a metatag dynamicly | Drupal 8

Change a metatag dynamicly

Submitted by editor on Fri, 07/28/2017 - 16:22
Question

How to change a metatag programaticly on drupal ?

The metatag module provide an API (hook) to alter all meta tags : hook_metatag_metatags_view_alter

Example:

NOTE : This is not the drupal best practice.

/**
 *
 * Implement hook_metatag_metatags_view_alter().
 *  - Translate 'description' metatag of the home page.
 * @param type $output
 * @param type $instance
 * @param type $options
 */
function mymodule_metatag_metatags_view_alter(&$output, $instance, $options) {
  if ($instance == 'global:frontpage') {
    // Use dpm or kint to get the field to change.    
    if (!empty($value = $output['description']['#attached']['drupal_add_html_head'][0][0]['#value'])) {
      $output['description']['#attached']['drupal_add_html_head'][0][0]['#value'] = "The new value";
    }
  }
}

Add new comment