Using Custom Fields for meta tag content

A fellow member of the SitePoint Forums asked how he could put meta description and meta keywords tags into his page's head. How can I use Custom Fields for meta description/keyword content?

I had never used Custom Fields before, but short of using a plugin to insert the meta tags, it seemed that using them would be the next best option.

Adding Custom Fields was easy enough to do in the Admin edit panel. And finding example code in the Codex was easy enough too. But the examples are for using the custom fields within a page's content, not in it's head.

Experimenting in my localhost test blog, I soon discovered that for the get_post_custom function to work it needed to be inside the Loop. Or more specifically, in this case, a Loop. Which makes obvious sense considering post_custom belongs to a post so it needs to be inside the Loop where the post information is available, :d'oh:

Custom Fields can be named just about anything, so I used:

meta-description
meta-keywords

for field names and entered some text for testing purposes.

Then in my theme's header.php file under the title tag I inserted

<?php
if (have_posts()) : the_post();
$custom_fields = get_post_custom();
$custom_meta_description = $custom_fields['meta-description'];
$custom_meta_keywords = $custom_fields['meta-keywords'];
if ( !empty($custom_meta_description[0]) )
{
	echo "<meta name='description' content='" . 
	 htmlentities($custom_meta_description[0]) . "' />\r\n";
}
if ( !empty($custom_meta_keywords[0]) )
{
	echo "<meta name='keywords' content='" . 
	 htmlentities($custom_meta_keywords[0]) . "' />\r\n";
}
rewind_posts();
endif;
?>

Admittedly hackish, and not the optimal way to get this accomplished, but it is easy enough to do and it works.