Add Drupal 8 meta tag depending on url

Here there will be a short note, where we will display the meta tag in the head depending on the array of urls we need. And we will do this through the theme function, since if the array of urls we need is large, then the usual condition of tweaks can pretty much clog the template.

So, inside the function function mytheme_preprocess_html(&$variables) { insert a similar code

$current_path = \Drupal::service('path.current')->getPath();
  $url = $_SERVER['REQUEST_URI'];
  $fake_url = array('/ua/node/59', '/ua/node/101');
  
  $meta_robot = [
    '#tag' => 'meta',
    '#attributes' => [
      'name' => 'robots',
      'content' => 'noindex, nofollow',
    ],
  ];
  
  foreach($fake_url as $fake){
      if(strpos($url, $fake) !== FALSE){
        $variables['page']['#attached']['html_head'][] = [$meta_robot, 'noindex, nofollow'];
      }
  }

A short explanation - first we get the value of the current url, after that we form an array, the elements of which are addresses for which we need to set a meta-tag. Next, we form what kind of meta-tag should be, in our case it will be"<meta name=robots content="noindex, nofollow"/>".

And at the end we put a retracement with a match condition, if in the current url we have a match to the address we need, then a meta tag is placed in the head of the page.

This is a simple and primitive construction, you can also add additional checks for the type of the node, if the site contains materials of different types.

Plain text

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