WordPress Tip: Adding Custom Fields in Posts

You can add custom fields below posts, and then pull out the values of those custom fields and insert them into a template. This reduces the sophistication behind styling post data, and automates the display in a template. This technique relies on the Custom Fields Template plugin.http://www.youtube.com/watch?v=L3VXnryN9iY Here are the main steps:

1. Install the Custom Field Template.

2. Navigate to Appearance > Editor and include this code snippet in your functions.php file:

function getCustomField($theField) {
global $post;
$block = get_post_meta($post->ID, $theField);
if($block){
foreach(($block) as $blocks) {
echo $blocks;
}
}
}

3. Configure the custom fields by going to Settings > Custom Field Template, expand the template content section, and add something like this:

[Day Number]
type = text
size = 10
output = true

Note: Unless you add output = true, the custom fields won’t work.

4. Go to Appearance > Editor and add this code into the template (such as single.php) where you want the value of the custom field to appear:

<?php getCustomField('Total Miles to Date'); ?>

5. To add a conditional statement around the getCustomField function (so that it only appears under certain conditions, such as the post being in a specific category), include this before the getCustomField function:

<?php if (in_category('3')){ ?>

… then insert your getCustomField functions …

and then close with this:

<!--?php } else { ?-->   <!--?php } ?-->

Here’s more information about conditional tags in WordPress.

7 thoughts on “WordPress Tip: Adding Custom Fields in Posts

  1. Denise Bass

    This is a great tutorial. Thank you. I was wondering if you can offer any tips for how to apply this technique on a page rather than in a post? Thanks!

  2. Drunk Hotline

    Finally! I been searching the internet for this solution and found your site. Thank you for taking the time to help people out…

    Is there a way to make the custom fields searchable? Meaning if a visitor uses the search form it will also search any of your custom fields.

  3. Tiffany

    This is a great tutorial…thank you! Quick question…I am building a site for a client and they need to fill in fields similar to the example you gave in the tutorial. But they may not need to fill in every single field on each entry. Is there a way to keep the field name from showing up when they need to leave that one blank? I’ve tried a few conditional statements, but I can’t seem to get anything to work.

    Thanks!

Comments are closed.