How to add variable meta tags depending on the node that is loaded?
The node has a picture and custom title field and the need to be variable.
What is the best practice to change them in: hook_preprocess_node()
?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI am aware that this does not directly answer the question, which was about adding in a preprocess function, but I would suggest that you also consider the metatag module, which is pretty full featured.
yes, you can, place this code in template.php in your subtheme folder
function yourtheme_preprocess_node(&$vars) {
$element = array(
'#tag' => 'meta',
'#attributes' => array(
'name' => 'robots',
'content' => 'index',
),
);
drupal_add_html_head($element, 'robots');
}
For me the following worked: I managed to load the current node in the hook_preprocess_node(). Based on this answer: How do I get the current node ID?
function module_name_page_attachments_alter(array &$page) {
$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();
}
$ogImage = array(
'#tag' => 'meta',
'#attributes' => array(
'property' => 'og:image',
'content' => 'location of the image'.$nid.'.png',
//my picture has the node id before the file format
),
);
$page['#attached']['html_head'][] = [$ogImage, 'ogImage'];
}