WP – using Custom Fields to insert content in the html head

I wanted to insert some custom styles and scripts into a post this week, to add a script and styles to generate a table of contents from the image captions. I continue to appreciate the cf_htmlhead tag in Cold Fusion but here we are in PHP and I’ve got the flexibility to create functionality I need so I opened up a couple of template files and inserted some code to return some specific custom field content saved in specific posts.
In case you didn’t know: WordPress allows you to create custom fields and then you can add code to “theLoop” to return the content of those custom fields.
Here’s how I used that;
I edited two template files: header.php and index.php adding an ob_start to the header before the closing head tag and then I added ob_get_clean tag to the template right after the start of “theLoop”. Essentially holding all the output generated between the tags and returning it after I returned the contents of the custom fields. That way my custom content was inserted into the header in a very w3c compliant way!

I called my custom field: htmlHead and once I added it to one post I have it available to all posts.
Best of all I can add multiple instances of the field and they are stored in an array. So I can add one for javascript and one for css, keeping them separate for easy editing.

Here are the code snippets:
(more…)