Hi everybody.

I was not happy with any of the solution for getting meta tags in drupal 7. Even the modules out there are not yet fully functional.
So i create some code my self to get this in my site. I would like to share what i have done.

First i created a new content type called Meta tags. This content type consists of

title : Used for the URL of the page where you want to add the meta tags to , no base path allowed.
field_meta_description : Used for the meta tag description you only put the description in here no formatting.
field_meta_keywords : Used for the meta tag keywords you only put the keywords separated by a comma in here no formatting.

Then i created a custom theme and copied the html.tpl.php to there. ( You can also move it to the theme you already use )
I edited this template from the following lines

<head profile="<?php print $grddl_profile; ?>">
<?php print $head; ?>

to this

<head profile="<?php print $grddl_profile; ?>">
 
 <?php 
     // start custome code for the meta tags.
     // meta tags are set in a node type meta_tags 
     // the title has to be the last part of the url
     // if the url is not found the stanaard text is used.
     
    $url = $_GET['q'];
    
    $result=db_query("SELECT nid FROM node WHERE type='meta_tags' and title=:url",array( ':url' => $url,));
    $nid = $result->fetchField(0);
    if(empty($nid)) {
        $metdes = "standaard description";
        $metkey = "standaard , key wordss";
    } else
    {
        $result=db_query("SELECT field_meta_description_value FROM field_revision_field_meta_description WHERE entity_id=:nid",array( ':nid' => $nid,));
        $metdes = $result->fetchField(0);
    
        $result=db_query("SELECT field_meta_keywords_value FROM field_revision_field_meta_keywords  WHERE entity_id=:nid",array( ':nid' => $nid,));
        $metkey = $result->fetchField(0);
    
  } // end else
    
    print "<meta name=\"Description\" content=\"$metdes\" />"; 
    echo "\n";
    print "<meta name=\"Keywords\" content=\"$metkey\" />";
    echo "\n";
    // end custom code for meta tags.
?>

  <?php print $head; ?>

This works for me i can now add meta tags to all pages even the once created by VIEW.
Just remember that the home pages is called node.

I hope this will help some people.

Marcel

Comments

juliangb’s picture

For reference for others looking for D7 meta tags support - http://drupal.org/project/metatags_quick might go some of the way for you.

mklynx’s picture

Yes i was using that but ran into problems with pages created by VIEWS.
That is the main reason i did it this way.

Marcel

valthebald’s picture

Hi Marcel,
I'm going to add support for entities other than nodes into next release of metatags_quick (hopefully next week).
I lack this feature as well :(

nlounds’s picture

Thanks, Marcel. This helped get me going. Here is what I came up with, since I wanted to use my page tags (taxonomy) instead of custom fields. Maybe someone will find it useful.


	// meta keywords based on tags	
	if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
		$nid = arg(1);
		$result=db_query("SELECT name FROM {taxonomy_term_data} INNER JOIN {taxonomy_index} ON {taxonomy_term_data.tid}={taxonomy_index.tid} AND {taxonomy_index.nid}=:nid",array( ':nid' => $nid,));
		foreach ($result as $record) {
			$metkey .= $record->name.", " ;
		}
		$metkey = substr($metkey, 0, -2); // trim comma from end of string
	} else {
		$metkey = "insert custom keywords here."; // default keywords
	}
	print "<meta name=\"Keywords\" content=\"$metkey\" />";

-Nate

d_l’s picture

When editing template files be aware that theme updates overwrite (edited) template files such as html.tpl.php.
I was caught out when marinelli beta was updated (I had followed the drupal 7 prompt to update modules and themes but forgot that I had edited the theme).
The answer of course is to create a clone of your theme to be edited to avoid having to rebuild the template files if auto-updated.

mklynx’s picture

I do not think a clone is a good way to go.
A sub-theme is easier when your base them is updated it will then automatically pick those updates up.
And no worries that something could get over written or you miss a important update.

Marcel

jymbob’s picture

Any pointers on how to make this work with clean URLs?

EDIT: whoops. Clean URLs doesn't affect this. My bad. However I was expecting it to use my URL aliases rather than 'node/5'. Is there a way to make it do this? Or have I got something set up wrong?

mklynx’s picture

I written this for drupal 7 so i do not know if it works in any other version.
But the line
$url = $_GET['q'];
picks up the url in drupal 7 it picks up the url alias ( clean url in drupal 6 ).

As fare as i know this should work in drupal 6 as well.

marcel

jymbob’s picture

Don't know if it's something with my setup, but if I have a page at example.com/foo which is internally node/3, it won't pick up details from a meta-tag node called 'foo' but will from one called 'node/3'

Is that the expected behaviour?

mklynx’s picture

No it is not. What version of drupal are you on.

Marcel

jymbob’s picture

Drupal 7.0 - sorry about the delay. RL got in the way for a couple of weeks.

Peters196’s picture

Thanks Marcel. That looks just what I want!
However, I have one problem! I copied html.tpl.php from [root]/modules/system/ to my themes folder at [root]/sites/all/themes/[mytheme]/ and added the extra lines to it. But it looks as though the system is still using the original file in the modules/system/ folder and not the new version! What do I need to do to force it to use the new version?
I am using Drupal 7.0 My theme is a copy (not a sub-theme) of Danland 7.x 1.0 with minor modifications. Neither My Theme nor Danland previously had a file called html.tpl.php.
Can anyone help?

Peters196’s picture

The reason it was still using the original file was that I had mis-typed the name of the new file! Sorry
However I have incorporated a small mod to Marcel's code to more easily define default meta-tags.
As before, create a new content node of type meta-tags and give it the title 'Default_node'
In there, place the meta description and meta tags you want to see on all the pages not over-ridden by a specific meta-tags node.

Replace the two lines between if(empty($nid)){........}else { with

{
$result=db_query("SELECT nid FROM node WHERE type='meta_tags' and title=:url",array( ':url' => 'Default_node',));
    $nid = $result->fetchField(0);
}

The next few lines are executed unconditionally, so remove the } // end else a few lines further down.
Now, if you want to change the default tags you need only edit the 'default_node' node rather than edit the php code!

lykle’s picture

I admit, noob here.

I tried to do what you are doing.
I copied html.tpl.php to the [root]/sites/all/themes/[mytheme]/ directory but I see no changes.
So I renamed the original in the [root]/modules/system/ directory and my site would not show anything.

Just to make it clear in my mind, do I move the file to the themes directory? Or do I copy it there?

I think I need to start understanding the structure of Drupal a little better before I start playing with these files.

Thanks for any help.
Lykle

artod4789’s picture

I'm fairly new as well, but you have to clear the cache once you've saved the file. I have my own html.tpl.php file in my theme directory, updated it to add some meta information in there directly (which I'm also having issues with), saved it, cleared the cache in the configuration > development > performance section. That worked for me.

psililisp’s picture

Thanks Marcel (and Nate) for your posts. I took your ideas and went with a similar approach for D7. For some reason, the more I think about it, the more I like having meta tags based on a URI path rather than a node / view / panel / etc. Anyway, here's what I did:

I followed Marcel's idea of creating a content type with three custom fields; page title, description, and keywords. The "Title" of those nodes would be the URI paths I wanted meta tags for, just as Marcel had done.

In template.php in my theme, I added the following to [theme]_preprocess_html(&$vars) {}

  // look up URI and see if we have a matching meta_tag_path node
  $vars['metatags'] = '';
  $query = new EntityFieldQuery();
  $result = $query
            ->entityCondition('entity_type','node')
            ->propertyCondition('title',$_GET['q'])
            ->propertyCondition('status',1)
            ->execute();
  if(!empty($result['node'])) // found meta tag
  {
      $meta_tag_nodes = entity_load('node',array_keys($result['node']));      
      $meta_tag_node = array_pop($meta_tag_nodes);
      $meta_page_title = $meta_tag_node->field_meta_page_title['und'][0]['value'];
      $meta_page_keywords = $meta_tag_node->field_meta_keywords['und'][0]['value'];
      $meta_page_description = $meta_tag_node->field_meta_description['und'][0]['value'];
      
      $vars['head_title'] = $meta_page_title;
      $vars['metatags'] = '<meta name="description" content="'.$meta_page_description.'"/><meta name="keywords" content="'.$meta_page_keywords.'"/>';
  }  

Then in my theme's html.tpl.php file I added the following to the HEAD area:
<?php print $metatags; ?>

Anyway. Though I'd share. And if someone notices something completely bunk with my approach, it'd be stellar to point it out.

valthebald’s picture

FYI: there is a wiki page comparing existing solutions for meta tags creation both for D6 and D7

Roulion’s picture

loopy1492’s picture

Thanks! From what I can tell, this method (physically adding it to the html.tpl.php in my theme) seems to be the only way to get a Content-Style-Type meta tag added to Drupal.