Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

WP Custom Fields, Part II: Tips and Tricks

[ Magnetic Fields ] As we have seen in our previous post, WordPress Custom Fields Part I, custom fields provide an excellent way to add flexible content to your posts and pages. By assigning various types of content to different custom fields, you gain complete control over when, where, and how to display the associated information. For example, sub-headings may be displayed in the sidebar, footnotes may be consolidated into a single region, post images may be displayed before the post title, and so on. In this follow-up article, we will review the basics of custom fields and then jump into a few custom-field tips and tricks.

Quick review of custom fields

Custom fields may be added when you create or edit any post, page, or custom post type. Each custom field consists of two variables, the key and its associated value. An example key would be “current mood”, and an example value would be “happy”. Each custom field remains associated with its corresponding post, but may of course be called outside of the loop and displayed anywhere via the theme template (e.g., sidebar, footer, et al).

There are several ways to retrieve and display custom field information on your pages. The first and easiest way uses the the_meta(); template tag, which always echoes an unordered list containing the attributes/values seen in the following example.

By default, <?php the_meta(); ?> gives us this:

<ul class='post-meta'>
<li><span class='post-meta-key'>Key 1:</span> Value for Key 1</li>
<li><span class='post-meta-key'>Key 2:</span> Value for Key 2</li>
<li><span class='post-meta-key'>Key 3:</span> Value for Key 3</li>
</ul>

Although this method is useful for general purposes, anything involving greater degrees of customization will require something a little more flexible. Fortunately, the get_post_meta() template tag provides the flexibility needed for advanced configurations. There are many ways to use this template tag, so let’s break away from the basics and explore some advanced tips and tricks.

Display values of a specific key

To loop through and display the values of a specific key, place the following within the loop of your choice, and change the “mood” value to that of your desired key value:

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

Display multiple values of a specific key

Each custom-field key may include multiple values. For example, if you listen to multiple songs during a given post, you may want to list them all with a key of “songs”. Then to loop through and display the multiple values for the songs key, we place the following code into the loop of choice:

<?php $songs = get_post_meta($post->ID, 'songs', false); ?>
	<h3>This post inspired by:</h3>
	<ul>
		<?php foreach($songs as $song) {
			echo '<li>'.$song.'</li>';
			} ?>
	</ul>

Notice the trick here: by changing the third parameter to “false”, we tell the function to return an array of the values for the specified key. A very handy trick for displaying multiple key values.

Display content only if a custom field exists

For cases when not all posts contain some specific custom-field key, use the following code to prevent unwanted, empty or incomplete markup from destroying the validity of your page:

// display an image based on custom-field value, if it exists

<?php $image = get_post_meta($post->ID, 'url', true);
	
	if($image) : ?>

	<img src="<?php echo $image; ?>" alt="" />

	<?php endif; ?>

Conditional display of custom-field data

Continuing with the previous technique, here is a basic code template for displaying a list of key values only if they exist:

<?php if(get_post_meta($post->ID, 'books', true) || 
	 get_post_meta($post->ID, 'music', true) || 
	 get_post_meta($post->ID, 'sites', true)
	 ): ?>

	<ul>
		<?php if(get_post_meta($post->ID, 'books', true)): ?>
		<li><?php echo get_post_meta($post->ID, 'books', true); ?></li>
		<?php endif; ?>

		<?php if(get_post_meta($post->ID, 'music', true)): ?>
		<li><?php echo get_post_meta($post->ID, 'music', true); ?></li>
		<?php endif; ?>

		<?php if(get_post_meta($post->ID, 'sites', true)): ?>
		<li><?php echo get_post_meta($post->ID, 'sites', true); ?></li>
		<?php endif; ?>
	</ul>

<?php endif; ?>

More conditional content based on custom-field values

Here’s another neat trick whereby custom-field values are used to determine which type of content appears on a page. In this example, we are checking the value of of a custom-field key called “hobbies”. Depending on the value of the hobbies key, different links are output on the page. Check it out:

<?php $value = get_post_meta($post->ID, 'hobbies', true);

	if($value == 'gaming') {
		echo '<a href="http://domain.tld/gaming/">Gaming Stuff</a>';
	} elseif($value == 'sleeping') {
		echo '<a href="http://domain.tld/sleeping/">Nap Supplies</a>';
	} elseif($value == 'eating') {
		echo '<a href="http://domain.tld/eating/">Dieting Advice</a>';
	} else {
		echo '<a href="http://domain.tld/">Home Page</a>';
	}

?>

Simplification and externalization

To clean up our source code a little, we can relocate the get_post_meta() function to the theme’s functions.php file. The immediate benefit here is one less parameter to include in the template tag. To do this, first place the following code into your theme’s functions.php file:

<?php function get_custom_field_data($key, $echo = false) {
	global $post;
	$value = get_post_meta($post->ID, $key, true);
	if($echo == false) {
		return $value;
	} else { 
		echo $value;
	}
}
?>

..and then call the function by placing this code in the desired location within your page template:

<?php if(function_exists('get_custom_field_data')) {
	get_custom_field_data('key', true);
} ?>

The only thing you need to edit here is the value of the “key” parameter, which should be the same as the key for which you would like to display value data. The second parameter is currently set as “true” so that the key value is echoed to the browser. To save the key value as a variable for further processing, change this parameter to “false”.

Streamlining attribute values

Using the same principle as described in the previous example, we can create a function that will streamline the display of custom-field images while providing localized control over their associated (X)HTML attributes. Given the typical example of a custom-field value containing a URL to a specific image, we create function whereby the image URL is retrieved and displayed along with a set of attribute values passed from the function call. We place this function in our theme’s functions.php file:

function get_attribute_data($key, $alt, $title, $width, $height) {
	global $post;
	$value = get_post_meta($post->ID, $key, true);
	if($value) {
		echo '<img src="'.$value.'" alt="'.$alt.'" title="'.$title.'" width="'.$width.'" height="'.$height.'" />';
	} else {
		return;
	}
}

We then place the following function call into the desired location within our page template file:

<?php get_attribute_data('image', 'Alt text for the image', 'Title text for the image', 150, 150); ?>

Once in place, this function first checks for the value of a custom-field key named “image”. If such a value exists, it is echoed to the browser within the requisite image ( <img> ) markup, which is also populated with the attribute values specified in the function call. The usefulness of this technique may also be applied to other types of custom-field values, such as links, lists, and so on.

Additional internal custom-field functions

In addition to the get_post_meta() function, there are three additional PostMeta functions that return arrays when used inside of the loop:

  • get_post_custom() — Returns array of key/value data for current post
  • get_post_custom_keys() — Returns array of key data for current post
  • get_post_custom_values($key) — Returns all values for a specific key for current post

Closing Thoughts

Hopefully at this point you have a clear understanding of how to implement custom fields. By generalizing the techniques described in this article and the previous tutorial, we may integrate virtually any type of content, associate it with any array of posts, and display the related content in segregated fashion according to the purposes of our design. Even better, using custom fields for particular types of content — featured images, footnotes, thumbnails, and other extra information — makes it easy to change the layout of your content on a sitewide basis.

References

About the Author
Jeff Starr = Creative thinker. Passionate about free and open Web.
GA Pro: Add Google Analytics to WordPress like a pro.

55 responses to “WP Custom Fields, Part II: Tips and Tricks”

  1. This has been incredibly helpful – you have no idea! I truly appreciate it

  2. I’m just starting to understand the power of custom fields and your post is really helping. Thanks!

  3. Thanks for very much for this tutorial. It’s excellent.

    I wonder if I could ask you a perhaps arcane question please.

    What’s the difference between:

    <?php echo get_post_meta($post->ID, 'myImage', $single=true) ?>

    and

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

    In other words, what difference does adding the “$single” make to the calling of the custom field? I ask because I’m comparing your really helpful tutorial with the Doc4 tutorial for Flutter (http://www.doc4design.com/articles/flutter-basic-usage) and notice this difference. I’m not sure of the distinction.

    Any help much appreciated.

    Kind regards
    Richard

  4. @Richard: great question. All I know is that the two statements are functionally identical, however you should refrain from restating the variable name when passing a value in the argument (as in your first example). Stick with just the value instead, especially with WordPress functions ;)

  5. I have a query about the multiple custom field values. How can I combine 2 multiple values? As in, if I need to insert 5 photos with the custom field “photo” and 5 links with the custom field “link” – each photo to be linked in order e.g. photo1 should link to link1, photo2 should link to link2 and so on… I tried but couldn’t figure out. Can someone help please?

  6. I have:

    ID, 'audio', true) || get_post_meta($post->ID, 'musicvideoo', true)): ?>

    display this if either musicvideoo or audio exists..

    But NOW how do we tell the system to NOT display that if either audio or musicvideoo exists..

  7. Jeff Starr 2009/12/15 4:07 pm

    Remember to wrap your code with <code> tags, folks — nobody can help you with half-eaten snippets..

  8. <?php if(get_post_meta($post->ID, 'audio', true) || get_post_meta($post->ID, 'musicvideo', true)): ?>

    show if musicvideo or audio exists

    <?php endif; ?>

    I want to know how to reverse the conditional statement with a !

  9. A less verbose way to display the custom field only if the field exists:

    <?php if(get('CustomField')) { ?>
           <? echo get('CustomField') ?>
    <?php } ?>

  10. Okay – I now realize we’re talking about WP Custom Fields here, not Flutter. Sorry!

  11. Lee Peterson 2010/01/11 11:36 am

    I’m trying to give my client an easy way to:

    • Use the key of ‘image’ multiple times for multiple images
    • Use timthumb script to resize proportionately
    • Create an image slide effect using Malsup Cycle script

    How would I combine multiple values and attribute types into one script?

    Seems I just can’t get it right:

    <?php $image = get_post_meta($post->ID, 'image', false); ?>
           <?php foreach($image as $the_image); {
                  echo '<img src="<?php bloginfo('template_url'); ?>/scripts/timthumb.php?src=<?php echo $the_image; ?>&h=170&w=220&zc=1&q=60" alt="<?php the_title(); ?>" />';
    } ?>

    This could be an excellent addition to your post above.

    Thank you!

  12. Hi perishable community,
    First of all I’m a new here and this site is very nice , very helpful.
    Could anyone help me pls. with displaying list of pages with at least 3-5 custom fields ? I’m almost for 14 days searching on internet, I have only found this article but there is only one custom field:
    http://www.wprecipes.com/how-to-use-a-custom-blurb-when-listing-pages
    , I asked there for the help to add more fields but no answer , Is it hard to add and display more fields ?
    I have changed my wp-pages into girl’s portfolios so i need list of girls with the girl’s names

    eg.:
    (page title-the name of the girl ),
    country,
    province,
    city,
    age and one thumbnail image (custom field)on the right.

    I am browsing internet 3 days 24/7 and i see only examples with one value & key , not with more , any help would be very appreciate.
    Thanks a lot Daniel

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
SAC Pro: Unlimited chats.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.