Thursday, January 15th, 2009 | 21 Days of WordPress Tips, Code, Tips, WordPress
This post originally appeared by Tim Grahl in our blog at Out:think Group, if Tim is referenced in the comments, that's why.
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:
<?php the_meta(); ?>
Would display something like:
<ul class='post-meta'>
<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>
</ul>
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…
$my_custom = get_post_custom();
echo my_custom[0]; // prints "Ralph"
echo my_custom[1]; // prints "Satan"
echo my_custom[2]; // 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.
if (get_post_meta($post->ID,'My Dog',true)) :
echo "My dog's name is " . get_post_meta($post->ID,'My Dog',true);
endif;
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.