WordPress Custom Fields, Part I: The Basics

by Jeff Starr on Wednesday, December 17, 2008 52 Responses

[ Diagram: Electric Field ] I recently developed a theme that makes heavy use of WordPress’ custom fields. The custom-field functionality of WordPress makes it possible to rig up just about any customized layout quickly and easily. Custom fields enable designers to organize post content into different sections, making it possible to create non-linear page layouts, with different types of content easily removed from the normal post loop and relocated to different parts of the document. This organizational and design flexibility has the added benefit of making it super-easy to update your content, redesign your theme, and handle blog maintenance in general. In the first part of this mini-series, we walk through the process of implementing and using custom fields; then, in part two, I will share some delicious tips and tricks to help you get the most out of everything that custom fields have to offer.

Learning by example: Custom image gallery

To help us understand the process of implementing and using custom fields, let’s imagine a hypothetical design scenario wherein you would like to represent each of your posts with a unique thumbnail image. Specifically, in your sidebar, you would like to display the ten most-recent of these thumbnail images as links to their corresponding posts, thereby enabling users to browse the images and follow through to the full post at their convenience. While there are probably several ways to accomplish this configuration, we are going to take advantage of WordPress’ custom-field functionality to learn about custom fields while getting the job done.

Step 1: Add custom images to posts

The first thing we need to do is to add the custom images to our posts. So, let’s say we currently have three posts, and will be writing many more posts in the future. Open the first post in the admin edit screen and scroll down to the “Custom Fields” area. Each custom field requires two parts: a “key” and a “value”. For this tutorial, our key will be specifying different “post-icon” values, so let’s use “post-icon” as the name of the key. If the key has been used at least once before, it will be available in the “Custom Fields” drop-down menu like so:

[ Screenshot: Pre-populated 'Key' field dropdown menu ]
The custom-field "key" will appear in the drop-down menu if it already has been used in another post

If the key is not listed in the drop-down menu (or if the drop-down menu fails to appear), we will need to add it by filling out the “Key” field. As this is the first post we are editing, we will create a key called “post-icon”, like so:

[ Screenshot: 'post-icon' value entered in 'Key' field ]
Since the custom key value does not yet exist, we add it to the "Key" field

Once the key has been specified in the appropriate field, we need to add its corresponding value. For this tutorial, we want each post to have its own custom thumbnail image, so we will use the image path as the value for this post’s “post-icon” key. Depending on the location of your custom images, your custom-field key/value pair should look like this:

[ Screenshot: Both 'Key' and 'Value' fields populated with data ]
With both "Key" and "Value" fields populated with the necessary data, we are all set

Click the “Add Custom Field” button to activate the custom field for the current post. Once done, this information is available to us in our WordPress theme files, thereby enabling us to call and display the custom post-images however necessary. Of course, the process we just went through should be repeated for all existing and future posts for which you would like to associate custom post-icon thumbnail images.

Step 2: Call and display the custom images

With the custom fields added to our posts, we are now ready to tap into some core WordPress functionality and display our custom post-images in the desired fashion. The function we will be using to retrieve the custom images is as follows:

<?php get_post_meta(); ?>

This is a native WordPress function designed to retrieve specific custom-field key values. The get_post_meta() function takes the following three parameters:

  • $post_id — defines the post from which the custom-field data is called
  • $key — defines the key of the desired custom-field meta value
  • $single — specifies whether to return the data as a string or as an array

Plugged into the get_post_meta() function, these parameters look like this:

<?php get_post_meta($post_id, '$key', $single); ?>

To specify the ID parameter, $post_id, for each post, we use “$post->ID”, which requires the function to be placed within the loop. For the $key parameter, we will use the name of the target key, which in this case is “post-icon”. And finally, because we want the key value returned as a string, we use “true” for the $single parameter. At this point our get_post_meta() function looks like this:

<?php get_post_meta($post->ID, 'post-icon', true); ?>

And we are almost there. As is, this code will simply return the custom-field value without printing it to the web page. So, we make one final edit to echo the data to the browser:

<?php echo get_post_meta($post->ID, 'post-icon', true); ?>

When placed in the loop, this function will output each post’s “post-icon” custom-field value, which at this point is simply a URL to the specific thumbnail image. For example:

http://domain.tld/path/custom-01.png

Not very useful for your visitors, however, by enclosing our function with a little code, we can easily transform that URL into an actual image that links to its corresponding post:

<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
	<img src="<?php echo get_post_meta($post->ID, 'post-icon', true); ?>" alt="Icon for Post #<?php the_ID(); ?>" />
</a>

That’s the ticket right there! Each post now includes its own custom icon that links directly to the single view of the post itself. In the next section, we will remove these custom images from their associated posts and display them in your sidebar as a consecutive thumbnail gallery.

Step 3: Display image gallery in teh sidebar

At this point, everything is setup, configured, and working great. We are successfully displaying custom post images that link to their associated posts. Now, to demonstrate the usefulness of WordPress custom fields, let’s remove our custom images from their respective posts and display them as a consecutive gallery within the sidebar. So instead of displaying this in the main column:

first post title
first post content
first custom image

second post title
second post content
second custom image

third post title
third post content
third custom image
.
.
.

..we have will display this in the sidebar:

first custom image

second custom image

third custom image
.
.
.

Without using custom fields, it is practically impossible to segregate intra-post data in this way. In other words, if we were to have included the custom-image URL along with the main post content, there would be no practical way 1 of separating the information from the remainder of the post; they would always need to be displayed together. By placing the URL data within a custom field, however, we are able to display the custom data wherever and however we wish. In our current example, we are going to sequester the thumbnail images into the sidebar.

The catch here is that our get_post_meta() function requires the loop in order to work. Thus, to display our thumbnails in the sidebar, we will need to create a secondary loop within the sidebar itself. Fortunately, we have a number of tools at our disposal. For this tutorial, let’s go with everybody’s favorite loop function, query_posts. Without going into detail about the query_posts() function, suffice it to say that it is an excellent way to create multiple, customized loops just about anywhere in your design. Here is the basic structure of our second loop:

<?php query_posts(); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

// content goes here

<?php endwhile; endif; ?>

So, after placing that secondary loop into our sidebar, we embellish it as follows:

<?php query_posts('showposts=10&offset=0'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
	<img src="<?php echo get_post_meta($post->ID, 'post-icon', true); ?>" alt="Icon for Post #<?php the_ID(); ?>" />
</a>
<?php endwhile; endif; ?>

As you can see, in the first line, we added two parameters — the first specifies the total number of loop cycles (ten, in our example), and the second indicates that we want the loop to begin with the most recent item (i.e., no offset). Beyond that bit of voodoo, we simply copy-&-pasted our previously marked-up get_post_meta() function into the “content goes here” portion of the loop.

Once we upload our newly edited sidebar.php file to the server, our web pages will feature the desired result: a nice thumbnail image gallery respectively linked to the ten most recent posts. Ahhhh.. feels so good! ;) Now let’s move on to some juicy custom-field tips and tricks! Actually, by the time I had finished this post, it was waayy too long (even by my standards) to publish as a single article. Thus, to alleviate the pain, I am breaking this post up into two parts. Stay tuned for Part II: Custom Field Tips and Tricks!

Footnotes

  • 1 I say “practical” because just about anything is possible with the right knowledge ;)

About the author

[ Jeff Starr ]

Jeff Starr is a web developer, graphic designer and content producer with over 10 years of experience and a passion for quality and detail. Jeff is co-author of the book Digging into WordPress and strives to help people be the best they can be on the Web. + Follow Jeff on Twitter and subscribe to Perishable Press for quality web-design content delivered fresh.


52 Responses
[ Gravatar Icon ]

Jin#1

Nice write up Jeff. I too use custom fields in my blog. I agree with you, without CF, I wouldn’t know how to give each blog post its unique look. I mostly use CFs for css settings. I did a quick tutorial on this you may be interested in:

http://www.8164.org/wordpress-custom-field/

Same concept though.

[ Gravatar Icon ]

Jeff Starr#2

Hi Jin, thanks for the visit and for sharing your custom-fields post. Your tutorial is well-written and provides additional information not covered in this article. There is certainly no lack of custom-field information out there, but I always find that writing about a topic is a great way to understand the information at a deeper level. Hopefully both of our articles will further help the growing WordPress community take advantage of custom fields in their own designs. Cheers! :)

[ Gravatar Icon ]

CantY#3

Wow, nice tutorial, i want implement it in my bog :)

[ Gravatar Icon ]

Jeff M#4

Excellent intro to the use of custom fields, Jeff. Folks need to learn this stuff, and your presentation is so easy to follow. I doubt, however, that I’ll be implementing it in my bog, nor in my kitchen or garage come to that ;)

Oh, and ‘teh sidebar’. You are so a joker 2.0, dude you crack me up!

Happy holidays and thanks again! You’re a star.

Jeff

[ Gravatar Icon ]

Susan#5

Custom fields are definitely a valuable wordpress tool in creating that special look. I don’t know what I would do without them on other sites.

[ Gravatar Icon ]

Shirley#6

Custom fields are great. They really add a whole lot of flexibility. On our site, we use custom fields for small galleries (similar to your example above), as well as for certain other template items (and features) that aren’t built in to WordPress.

Great tutorial. It might be a good idea to link to this article from the WP Codex.

[ Gravatar Icon ]

Jeff Starr#7

@Jeff M: Thanks for the positive feedback! I think custom fields would work great in your garage! LOL ;) Happy Holidays to you as well! Thanks for being a part of Perishable Press in 2008 — looking forward to hearing more from you in 2009! Cheers!

@Susan: That is definitely the take-home message for this post: you can achieve virtually any layout by using the functionality of WordPress custom fields. Thanks for the comment :)

@Shirley: I totally agree, I have been using them more and more on the sites I develop. Even for segregating things like subtitles, footnotes, and code examples, custom fields enable long-term design flexibility. They are a little more work up front, but definitely pay off in the long run. Also, thanks for the idea of linking from the Codex — hopefully others will find it helpful as well!

[ Gravatar Icon ]

Hemanth#8

Interesting. I use a theme in one of my blogs with a custom field to enter an image name which will b used as a thumb nail for the post. It really changed the appearance of the entire blog, thanks to WP custom fields.

Btw. Nice article, Bookmarked. :)

[ Gravatar Icon ]

teddY#9

Wow another mind-blowing post, Jeff! Seriously, your tutorials are extremely useful and they appeal to me very much like what a Wordpress-centered Wiki will. Although there are a lot of information out there on Wordpress custom fields (like on WP Codex), yours is the most comprehensive on so far (and it’s only part one, golly!).

I’ve never been able to understand custom fields completely, even when I’ve googled for how we should use them, in the shoes of a designer or a blogger. I never knew that so much can be done with custom fields and how helpful it can be when it comes to delivering custom content to readers.

What really surprises me is that to extract information from custom fields, a simple loop is what we really need (with some knowledge of WP php tags, that is) - it’s fairly straightforward and simple. Thank you so much for sharing the important codes - they are a really good headstart for amateurs like me.

And when I’m done with dinner, I’ll continue with Part II ;) thanks!

p/s: There’s a minor typo for the H2 header for Step 3: “the” instead of “teh”. I’m sorry :P

[ Gravatar Icon ]

Jeff Starr#10

@Hemanth: Absolutely! Thanks for the positive feedback — Much appreciated :)

@teddY: You are too kind! Thank you for the great comment. It is very encouraging to hear that my articles are useful and appreciated. They do take some time to produce, but hearing such excellent feedback really fuels the fire and encourages me to keep on sharing this type of information. Great to hear from you teddY — I hope you enjoy “Part II” as well! (oh, and the typo was intentional — an attempt at a little “leet speak”! Thanks for pointing it out though!:) Cheers and Happy New Year to you and yours! :)

[ Gravatar Icon ]

eddai#11

what a descriptive post for custom fields, never understood before its functionality and now at least i understand its basics.
the more i read,i will get it.
Many Thanks Bro!

[ Gravatar Icon ]

Jeff Starr#12

@eddai: My pleasure — glad to be of service! :)

[ Gravatar Icon ]

Kim Woodbridge#13

Oh Jeff - Thank you! While I sort of understood custom fields I now get it because of this tutorial. I really appreciate how you include details for every step. Many would have said “now put it in a loop in the sidebar” but instead you went through all of the steps. Ok - now I’m going to read Part 2

[ Gravatar Icon ]

Jeff Starr#14

Glad to be of service, Kim! Some people may prefer to forego the more detailed explanations, but many articles — especially the ones covering the basics of a topic– simply wouldn’t be complete without them. As always, thank you for the positive feedback — I hope you enjoy Part 2 as well.

[ Gravatar Icon ]

Bobo#15

How do I use a conditional with this?

Suppose I want to use this logic:

If this post’s custom field with key “thumbnail” contains nothing, do not display it.
However, if the field “thumbnail” contains a value, then display it.

Thanks.

[ Gravatar Icon ]

Jeff Starr#16

@Bobo: Check out the follow-up post to this article. In it, you will find the exact method you describe, along with many others as well. :)

[ Gravatar Icon ]

Mike#17

This is an excellent written article. I have been trouble finding an easy and effective way to do this as I wanted the same image functionality like on most news websites. Just a quick note, for the sidebar image thumbnails, if I wanted the excerpt of the post to also appear, would it just be as straight forward as to include the php excerpt script?

[ Gravatar Icon ]

Jeff Starr#18

@Mike: Absolutely. Use the loop provided in the article and place any WordPress tag (including the_excerpt()) wherever you wish. Great question — Thank you!

[ Gravatar Icon ]

C#19

Thank you so much!

[ Gravatar Icon ]

Michael#20

This is actually the clearest lesson on how to output custom fields that I’ve found (the Codex is pretty vague on the whole “$post->ID, ‘post-icon’, true” thing). Thanks a lot.

[ Gravatar Icon ]

Jeff Starr#21

My pleasure, Michael — thanks for the positive feedback :)

[ Gravatar Icon ]

Tommy#22

Great post Jeff, it has been really helpful.

One issue I still have regarding custom fields is that when I implement it at the very end of the wp loop, my custom field values display below my plugins. I want i want my custom field values to display after my content and above my plugins. I am currently using wp 2.8 with the “addthis” plugin activated on all post. Any suggestions on how to fix this?

[ Gravatar Icon ]

Jeff Starr#23

@Tommy: You might try looking around in the plugin for the add_filter() function and set a lower priority for it. The filter should look something like this:

add_filter('the_content', 'add_this');

The default is “10″, so if there is nothing listed then you may want to try increasing it to a higher value (like “999″). Lower numbers correspond to earlier function execution.

For more information, check out the Codex:

http://codex.wordpress.org/Function_Reference/add_filter

[ Gravatar Icon ]

Tommy#24

hey jeff, thanks for the suggestion. I’ve tried lower the priority of the functions, but because it executes within the ‘the_content’ loop it will always appear before the content in my custom fields. I haven’t found an easy way to implement contents from a custom fields in the ‘the_content’ loop, i have only been able to have it execute before or after “the_content”

[ Gravatar Icon ]

Jeff Starr#25

Hey Tommy, a few more things that come to mind:

  • Hard-code the plugin into the desired location in your theme file
  • Look into putting the_content in a variable and extracting the target contents via PHP
  • Use some CSS trickery to move the custom-field content above the plugin content
  • and, if all else fails, ..use JavaScript!
[ Gravatar Icon ]

Tommy#26

thanks jeff. i’ll try ur suggestions this weekend.

[ Gravatar Icon ]

Karl#27

Hi,

Just wanted to thank you for this outstanding tutorial. I spend a few hours banging my head against the wall trying to follow tutorials from other sites, including the official wordpress site, then I came across yours. It worked like a charm the very first time.

Thank you, thank you and once again, thank you!

[ Gravatar Icon ]

Jeff Starr#28

@Karl: You are most welcome! :)

[ Gravatar Icon ]

Flavio#29

Great, It was useful to me in the video section of the http://calvario.org.br/ site.
Thanks

[ Gravatar Icon ]

Flavio#30

I was failing while I didn’t put the word “echo”.
Thanks

[ Gravatar Icon ]

Daniel Balfour#31

This is an excellent tutorial (and Jin’s as well!)
Thank you for taking the the time and contributing to other people’s WordPress blogging experience!

[ Gravatar Icon ]

Lewis Litanzios#32

You’ve done it again Jeff old son. First link out of Google I could make sense of (and has working code (2.8.5)).

Cheers bro.

[ Gravatar Icon ]

Ruben#33

Hello. I now it is possible to have a one stylesheet file per post. But im having too much troubles. I read this on smashing magazine

I put this code in the header.php of my theme

ID, "customStyles", true);
if (!empty($customStyles)) { ?>
<link rel="stylesheet" href="" type="text/css" media="screen" />

Then in the custom field

i put this

Name: customStyles
Value: all the href of my new stylesheet but i doesnt work.

Can somebody help me please !

Thanks in advance

[ Gravatar Icon ]

ldexterldesign#34

@Ruben Use the body classes output by WP on each individual page to hang your unique page styling off.

[ Gravatar Icon ]

Chad#35

Great post! very easy to follow and very well written. I was wondering how more than one image could be displayed in the same post using the same custom field input key? So, 2 image or more could be displayed in the active post… does this make sense, I have not found much on this and I like the simplicity of custom fields, but would be interested in adding more images to posts if needed.

Thanks and keep up the great tutorial writing.

Chad

[ Gravatar Icon ]

Jeff Starr#36

Hi Chad, I think this should help you out:

Awesome Image-Attachment Recipes for WordPress

It covers many different techniques for including images attached to posts. Also, I think that Justin’s excellent plugin, Get The Image, may also assist in forging a solution.

[ Gravatar Icon ]

Daan#37

Thanks!!

[ Gravatar Icon ]

James#38

thanks for the tutorial, I’m using custom fields on my website but I am struggling to order the posts by the custom field - “price” because each number has a £ sign before it. Do you have any suggestions?

[ Gravatar Icon ]

Sidenote#39

Nice tutorial, just implemented on my site. Thank you for sharing.

[ Gravatar Icon ]

Justin Lascelle#40

Thanks a ton for this clear write-up. I’m currently involved in a project where this information will come in very handy. Keep up the great work.

Trackbacks / Pingbacks
  1. WordPress Custom Fields, Part II: Tips and Tricks | bloground.ro - Blogging resources, WordPress themes and plugins for your development
  2. Using Thumbnails for Excerpts Plugin with Query Posts to Make a Custom Sidebar Block in WordPress | (Anti) Social Development
  3. 20+ Tutorials and Resources for Working with Custom Fields in WordPress | Vandelay Design Blog
  4. Create a Stunning Lightbox-Style Random-Post Header Gallery
  5. WordPress Custom Fields 101 - Tutorial for the Total Newbie | Wordpress
  6. Usare i “Custom Fields” di Wordpress – Parte 1 | Tekné
  7. 6 Useful Coding Solutions For Designers And Developers - Smashing Magazine
  8. Using WordPress Custom Fields (in 2 parts) » Critical Flare
  9. 65 Of The Best WordPress Tutorials « Junkiee.Net
  10. How To: Customize Your Wordpress Site – ThinkDoBeCreate
  11. Extend WordPress With Custom Fields - Smashing Magazine
  12. Complete Guide to the Awesome New Features in WordPress 3.0 | Digging into WordPress
Comments are closed for this post

If you have or need further information, contact me.



Attention: Do NOT follow this link!