How to Add noindex meta Tag on Single or specific Node using Hook

How to Add noindex meta Tag on Single or specific Node using Hook

Using if $nid is equal to added so add noindex in the head tag for this we can using theme_preprocess_html() hook.
 

function example_theme_theme_preprocess_html(&$variables)  
 {  
   // added tag in html for single page '<meta name="robots" content="noindex" />'  
   $node = \Drupal::routeMatch()->getParameter('node');  
   if ($node instanceof \Drupal\node\NodeInterface) {  
   // You can get nid and anything else you need from the node object.  
   $nid = $node->id();  
   }  
   if($nid == 136){  
     $noindex = [  
       '#tag' => 'meta',  
       '#attributes' => [  
         'name' => 'robots',  
         'content' => 'noindex',  
       ],  
     ];  
    $variables['page']['#attached']['html_head'][] = [$noindex, 'noindex'];  
   }  
 }  


Clear Drupal cache and check you given change on the frontend.

Follow us on below social media for such amazing web development-related and drupal related tricks and tips.