background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount
Eric.London's picture

Most SEO tutorials claim that meta keywords are not very important to search engines. But, if you insist on inserting meta keywords for each node's taxonomy terms, this tutorial will show you how to accomplish this. I added the following function to my template.php file in my theme.

<?php
function _phptemplate_variables($hook, $vars) {
 
// check for page scope
 
if ($hook == 'page') {
   
// ensure this page is a node view
   
if (is_object($vars['node'])) {
     
// get a list of taxonomy terms for this node
     
$terms = taxonomy_node_get_terms($vars['node']->nid);
           
     
// ensure terms exist
     
if (is_array($terms)) {

       
// loop through terms, and collect the names
       
$t = array();
        foreach (
$terms as $k => $v) {
         
$t[] = $v->name;   
        }
               
       
// ensure names exist
       
if (is_array($t)) {
         
// implode the terms into a string and add to the head variable
         
$vars['head'] .= "<meta name='keywords' content='" . implode(",", $t) . "'>";
        }

      }

    }
       
  }
  return
$vars;
}
?>

To verify this code is working, check out the tags I used on this page and then view the source. Hopefully, they match!

(NOTE: my homepage is a view, so there show not be any meta keywords.)


NOTE: when I upgraded my theme to Drupal 6, I had to update this above code:

<?php
function MYTHEME_preprocess_page(&$variables) {
  if (
is_object($variables['node']) && is_array($variables['node']->taxonomy)) {
   
$tags = array();
    foreach (
$variables['node']->taxonomy as $tid => $term) {
      if (!
in_array($term->name, $tags)) $tags[] = $term->name;
    }
       
    if (
count($tags)) {
     
sort($tags);
     
$variables['head'] .= "<meta name='keywords' content='" . implode(",", $tags) . "'>";
    }
  }
}
?>

Syndicate content