display content only if a custom field exists in WordPress
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

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>';
	}

?>

You may want to check :

  1. display custom field
  2. get custom fields value
  3. automatically create a custom field when a post is published
  4. get custom fields easier hack
  5. get posts with a specific custom field/value

Post a Comment

Your email is never shared. Required fields are marked *

*
*