How to: Automatically add a default set of Custom Fields to each post in WordPress


PrincipiaPilot.org screenshot showing Custom Fields being used in a template

One of the neat things about WordPress is how easy it is to add custom metadata to a given page or post that you can then use in a template to display structured information. I’ve been using this technique for a while now to extend the basic WordPress elements of title, body, excerpt, etc and allow the creation of easily editable information-rich content.

Before now I’ve used the built-in WordPress Custom Field functionality in the Add New screen where you select previously created custom fields from a drop-down list that is limited to only showing 30 items. This is quite cumbersome as you have select each field you want to add to the entry and enter the value, click the Add Custom Field button, then repeat for however many custom fields you want to use. Needless to say, this can be frustrating to have to remember to do every time, especially for non-technical clients.

The Old Way:

Selecting a Custom Field (the old way)

During a recent site conversion to WordPress that involves 4-6 custom fields for each post, we finally decided that there must be a better way, and ended up finding a WordPress plugin that is so good that it should probably be added to WordPress core, it is so highly useful. The plugin is called Custom Field Template and is developed by Hiroaki Miyashita.

The New Way:

Custom Field Template WordPress plugin screenshot

Using a simple set of options to define the template you want to use is easy. After downloading and activating the plugin, go to Settings > Custom Field Template to define your template. One is provided for you to show you the possible template values. You can set up two separate custom field template designs.

This is the code used to generate the Custom Field Template form shown in the screenshot above:

Template Instruction

<strong>Story Template Metadata Instructions <em>(All fields are optional)</em></strong><br /><br />
1. Use this form to enter metadata about this story.<br />
2. Each item will get assigned to the correct Custom Field for use in the display template.<br />
3. Click the <strong>Save</strong> button to save the values.<br />
<br />

Template Content

[summary_deck]
type = textarea
rows = 3
cols = 50
label = Summary Deck:

[byline_writer_name]
type = text
size = 35
label = Byline Writer Name:

[byline_writer_title]
type = text
size = 35
label = Byline Writer Title:

[byline_writer_picture_url]
type = text
size = 54
label = Byline Writer Picture URL:

[lead_photo_caption]
type = textarea
rows = 3
cols = 50
label = Lead Photo Caption:

[lead_photo_credit]
type = text
size = 35
label = Lead Photo Credit:

[lead_photo_url]
type = text
size = 54
label = Lead Photo URL:

Then set this setting to true by checking the box to make the form look prettier:
Custom Field Template WordPress plugin setting

Next, I tweaked the Admin CSS settings to right-justify the labels:

#cft dl { clear:both; margin:0; padding:0; width:100%; }
#cft dt { float:left; font-weight:bold; margin:0; padding: 0 8px 0 0; text-align:right; width: 20%; }
#cft dt .hideKey { visibility:hidden; }
#cft dd { float:left; margin:0; text-align:left; width:70%; }
#cft dd p.label { font-weight:bold; margin:0; }
#cft_instruction { margin:10px; }

Click Update Options to save the settings and then go to Posts > Add New to see the form in action. You may need to go back and forth a couple of times to get your text field sizes just right and to put them in the right order you want them in.

Using the Custom Fields in a template

So how do these values get displayed on your page?

Simply edit your template PHP file to look for custom field values and then display them where you want them if they’re present.

This is how I do it for the Principia Pilot site. This code goes at the top of the template for single.php

<?php
// Retrieve custom meta values from post if they're present
$byline_writer_name = htmlspecialchars(get_post_meta($post->ID, "byline_writer_name", true));
$byline_writer_title = htmlspecialchars(get_post_meta($post->ID, "byline_writer_title", true));
$byline_writer_picture_url = htmlspecialchars(get_post_meta($post->ID, "byline_writer_picture_url", true));
$lead_photo_url = htmlspecialchars(get_post_meta($post->ID, "lead_photo_url", true));
$lead_photo_credit = htmlspecialchars(get_post_meta($post->ID, "lead_photo_credit", true));
$lead_photo_caption = htmlspecialchars(get_post_meta($post->ID, "lead_photo_caption", true));
$summary_deck = wptexturize(get_post_meta($post->ID, "summary_deck", true));
?>

Now each of the possible Custom Fields are available as PHP variables that can be checked for content.

This code example shows the “summary deck” being displayed on the page if it has been entered on the create content screen:

<?php
// Show summary deck if we have one
if ($summary_deck != "") {
    echo '<h3 class="summary-deck">' . $summary_deck . '</h3>';
}
?>

Using this excellent plugin, you can set up select lists, radio buttons, check boxes and more to help you populate your Custom Fields more easily if you prefer that to using simple text fields. You can also specify default values to use for the custom fields so you don’t have to type them in every time.

Plugin Default Template Options

These are the default options included by the plugin:
[Plan]
type = text
size = 35
label = Where are you going to go?

[Plan]
type = textfield
size = 35
hideKey = true

[Favorite Fruits]
type = checkbox
value = apple # orange # banana # grape
default = orange # grape

[Miles Walked]
type = radio
value = 0-9 # 10-19 # 20+
default = 10-19
clearButton = true

[Temper Level]
type = select
value = High # Medium # Low
default = Low

[Hidden Thought]
type = textarea
rows = 4
cols = 40
tinyMCE = true
mediaButton = true

Which displays a form that looks like this:
Custom Field Template WordPress plugin screenshot - Default form options

Summary

This plugin addresses a key need when using Custom Meta Fields in a WordPress custom template design — making it as easy as possible to enter values time after time on multiple pages or posts. There are a bunch of other neat options this plugin offers to make the authoring experience even easier. This is now on my “must install” list of essential WordPress plugins.

Please support Open Source by donating to the plugin author

If you use this and like it, I highly recommend sending a nice donation to the plugin author to help support ongoing development and to say thanks. This plugin will save you and your clients a lot of time and frustration. Thanks Hiroaki!


Requirements

Requires WordPress 2.1 or higher.

Click here to download Custom Field Template plugin from WordPress.org


20 responses to “How to: Automatically add a default set of Custom Fields to each post in WordPress”

  1. Hey,

    I didn’t understand how to insert the custom fields in a post. I need a custom field template to be inserted at the bottom of a post, but I don’t know how to do that.

    I added you to my MSN list. Thanks.

  2. Mihnea,

    Look at the “Using the Custom Fields in a template” section above. To actually display the custom fields, you have to retrieve them and then add them to your template.

    I don’t think this plugin supports adding a Custom Field Template to the public view of a site (it’s a backend admin view only I believe).


    Gabriel

  3. Oh, no! I don’t to display the CFT. I want to create a box that would appear at the bottom of the post (ex: TechCrunch has such a box).

    The values from the box should be inserted by the admin using the CFT. I understood what this plugin does, but I didn’t figure out how to put that box in the single post page.

    I’ve tried the WordPress indications for Custom Fields usage with the_meta() function, but it displays all the templates:(

    Thanks for the quick reply,
    Mihnea

  4. hey gabriel,

    thanks for helping us out with this nice plugin. unfortunately i can’t get it to work for me. i left all the default data intact after i installed it. then i tried to use the code you provided above to pull the custom field data into my blog, but nothing happens. what works though is the regular <>ID, ‘fill me with the key’, true); >> but that one also dosen’t work properly. for example it doesn’t list the checkboxes, only the first active checkbox is being displayed. do you have any advice?

    thanks
    marc

  5. I am very new to wordpress and I wanted to say thank you so much for your instructions and clarifications on the use of the Custom Field Template plugin. Wasn’t really sure how to use this plugin or IF this plugin would even solve the problem I was having. Tried to use it once before but got flustered and deactiviated it. Then I found your site. Thank you so much for clarifying how to use this plugin.

  6. Hey,
    to everyone who has problems with get_post_meta, it didnt’t work for me, but get_post_custom_values(‘key’, $post->ID) does work.
    It returns an array, to access the value use key[0].

  7. Hey,
    Can this plugin add a Custom Field called ‘Thumbnail’ to every post and for Value insert a unique URL such as http://img.youtube.com/vi/xyzVideo/0.jpg ?

    This is what the eVid theme (by Elegant Themes) requires so that each video show a big image and a small image (thumbnail).

    My video blog updates on autopilot with the MyVideoBlog plugin.

    I has over 100 posts and I don’t want to add the custom field to each post manually? So can this plugin do this automatically?

    Many Thanks,
    Nefeli

  8. Many thanks! I’ll be using your system for a project actually… this comes really in handy. Btw, you could add a Twitter button to your site, because this post deservers a Retweet 😉 ! Cheers.

  9. Likewise, a great post. Did clear some things up. I just went through a nice custom post tutorial (newbee here) and having create the custom fields for each post is nuts. This plug-in is a lifesaver.

    My question concerns CSS. I’ve looked through every detail I could find of the CFT settings and can’t find a comprehensive way to tweek CSS. Is the Admin CSS the only way? And how in that option do we style things like margins, padding, or even color.

    Any directions are very welcome.

    Thanks

  10. Hi,
    1.first of all does it work with 3.14?
    2.i disable the first template and the i create a similar one at the bottom but i cannot get it to show in the “add new” page/post.
    3. the input type=file when i use it with the template 0 i can see the image uploaded but when i use the ID, ‘FileUpload’, true ); ?> i only see a number.

    thanks

  11. This blog post should either be extended or the author of the plugin needs to write how to even use this plugin. I’ve been tackling with this for a few hours.

    Can’t get custom fields template to show at all anywhere in posts or page.

  12. **Update**

    I mentioned that above because if someone followed this blog ( the only resource to this plug ), it looks like you omitted a few steps that would actually see this through to working. Following this blog doesn’t lead to the same outcome that you show.

  13. This guide at least got me to get this to work. There is little documentation for this one. But i didn’t really want to do things this way. I assumed that after filling in the custom field template info on a page, i’d just have to put [cft] in the content for it to display, but it doesn’t work. Any guide on this method?

Leave a Reply to CocoCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

sell diamonds