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:
<?php $image = get_post_meta($post->ID, 'url', true); if($image) : ?> <img src="<?php echo $image; ?>" alt="" /> <?php endif; ?>
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>';
}
?>
