Ed: This article is part of the 21 Days of WordPress Tips
Last week I showed you how to make custom fields easy to use for the back end of WordPress. But once you get the content in there, how do you successfully extract it and use it in your theme?
There are a few template tags that are useful in displaying custom field data:
- the_meta() – This is the simplest way to display the custom fields. It simply prints each custom field attached to the current post showing the key and value in an unordered list. While this is a very simple solution, it gives you almost no control.
<?php the_meta(); ?>
Would display something like:
<li><span class='post-meta-key'>My Dog:</span> Ralph</li>
<li><span class='post-meta-key'>My Cat:</span> Satan</li>
<li><span class='post-meta-key'>My Fish:</span> Gills</li>
If you want to simply list out all the custom field data for each post, this is the way to go. But if you want more control…
- get_post_custom() – This template tag is much more useful. It returns a multi-dimensional with all of your custom field data. Using the same example as above:
$my_custom = get_post_custom();
echo my_custom; // prints "Ralph"
echo my_custom; // prints "Satan"
echo my_custom; // prints "Gills"
The biggest issue I have with this function is the array is returned with the keys as 0, 1, 2, etc instead of an associated array with the key being the custom field key. This causes problems when you have a lot of custom fields and you’re trying to arrange them on a page in a certain way.
- get_post_meta() – This is the template tag I use the most for displaying custom fields. It’s simple, easy to use and gives you complete control. Here’s a typical way I’d use it in a theme:
- The ID of the post/page you want to show the custom field data for. In most cases you’ll be using this inside the loop in your theme where the WordPress $post variable will be set. So you can simply use $post->ID to get the right post/page ID.
- The custom field key that you want to pull the custom field data for
- Whether you want to return the results as a string (true) or an array (false). Since we simple want to print out the custom field content, we set it to true to return a string.
if (get_post_meta($post->ID,'My Dog',true)) :
echo "My dog's name is " . get_post_meta($post->ID,'My Dog',true);
The get_post_meta() function has three parameters you can pass:
As you can see in the above code, I wrapped the echo statement in an if statement. What this does is check to make sure there is anything in the custom field before you try and print it to the screen. That way you won’t show an unfinished statement of “My dog’s name is” if for some reason the custom field box wasn’t filled in. It will simple leave off the whole thing.
Those are three of the most widely used ways of displaying custom field data in your themes. Hopefully it will help add more functionality than ever to your next WordPress site.
January 15, 2009