Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm messing around with Custom Meta Boxes in WP for the first time and was wondering how I go about displaying the fields that only have values attached to it.

For example I've got a meta box with an ID of "floorplans" and a field with an ID of "image", which I'm able to display like so:

 <img src="
   <?php $custom = get_post_custom($post->ID, 'floorplans', true);
   echo $custom["image"][0];?>
 "/>

How do I make this conditional, so it only displays the field when a value is present?

share|improve this question

1 Answer 1

<?php if ( get_post_meta($post->ID, 'floorplans', true) ) : ?>

Your code

<?php endif; ?>

Should do it... I believe

share|improve this answer
    
That's perfect! Can't vote up as I haven't got 15+ reputation yet. May I ask why you used get_post_meta? What's the difference between that and get_post_custom? Thanks again. –  realph Apr 2 '12 at 21:06
    
EDIT: Sorry, for some reason when the value IS there it's not showing. It's not displaying at all, whether the value is there or not. –  realph Apr 2 '12 at 21:20
    
Oh wait... I'm trying to understand your setup. Your actual key for the meta data is image? You may want to swap floorplans with image in my code. Also check: codex.wordpress.org/Function_Reference/get_post_custom and codex.wordpress.org/Function_Reference/get_post_meta I don't thing get_post_custom accepts the parameters you are passing it? get_post_custom returns all meta data attached to a post, get_post_meta can return specific meta data. –  Rev. Voodoo Apr 3 '12 at 11:15
    
If you only happened to have 1 custom field in use, get_post_custom only happened to return that. BUt if you had 20 custom fields in use, get_post_custom would return all of them. You may be better off echoing get_post_meta instead, if you are only using 1 field. And I'm not sure if your key is image or floorplans by your description... but I'm thinking it's actually image, which is why my conditional would fail. –  Rev. Voodoo Apr 3 '12 at 11:21
    
MY above comment isn't well worded, and I'm too late to edit it... so I don't think the 'floorplans', true portion of your code does anything. I"m not 100% familiar with get_post_custom, but it grabs all meta associated wit hthe post. Your next line of code echoes out all data associated with the first 'image' key. So you could probably more simply just echo get_post_meta post->ID, 'image', true to get your meta data... if you aren't needing to work with multiple custom field entries per post –  Rev. Voodoo Apr 3 '12 at 11:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.