How to use Custom fields in your themes

July 10th, 2009 in Tutorials by Michael    Tags:

Today I will give you a very basic but at the same time very useful WordPress trick. How to get values from custom fields.

To be honest it’s very easy to achieve. Let’s modulate a situation: during the post creation process you’ve specified a custom field with the name “thumbnail_image” and as a value you’ve provided an URL to the image on your server. What’s next? Open a single.php template in your favorite text editor program. And prepare yourself for hours of coding and hacking…

Just kidding.

All we need to do is just 2 things:

  1. Check, does the post have a value entered inside of the custom field we are looking for.
  2. If the answer to the 1st question is positive, then wrap our value from the custom field with necessary HTML code and output it to the screen.
<?php if (get_post_meta($post->ID, "thumbnail_image", $single = true)): ?>
<img src="<?php echo get_post_meta($post->ID, "thumbnail_image", $single = true); ?>" alt="<?php the_title(); ?>" />
<?php endif; ?>

Believe it or not, but we are done!


Share your comment

Name Your Message
Email Website * We know you have something to say