Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Change a metatag dynamicly

By editor , 28 July, 2017
Question

How to change a metatag programaticly on drupal ?

Add meta tag from controller

Example: Add <meta http-equiv="refresh" content="30">
$data = [
  '#tag' => 'meta',
  '#attributes' => [
    'http-equiv' => 'refresh',
    'content' => '30',
  ],
];
$output['#attached']['html_head'][] = [$data, 'refresh'];

 

And also:

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";
    }
  }
}

Tags

  • Drupal 8
  • Code
  • SEO
  • Hook

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer