tags:

views:

145

answers:

4

I have some user-submitted variables that I want to display in a different part of my site like this:

<div class="pre_box">Term: </div>
<div class="entry"><?php $key='term'; echo get_post_meta($post->ID, $key, true); ?></div>

Occasionally, these variables might be empty in which case I don't want to display the label for the empty variable. In the example above I would want to hide the <div class="pre_box">Term: </div> part. Is there some simple way to check if a php variable like the one above is empty and prevent the label from being displayed?

Update, here is the code using !empty

<?php $key='term' ?>
<?php if( !empty( $key ) ): ?> 
<div class="pre_box">Term: </div>
<div class="entry">
<?php echo get_post_meta($post->ID, $key, true); ?>
</div> 
<?php endif; ?>

However, this still displays the content no matter what. I think the problem might be in the way I am defining the $key variable. Im trying to pull data from a custom field set in a wordpress post - thats what the $post->ID business is all about.

+1  A: 
<?php if( isset( $var ) ): ?><p><?php echo $var ?></p><?php endif; ?>

If $var is set it will display the paragraph with $var, otherwise nothing will be displayed

Galen
`<?php if( isset( $key ) ): ?><div class="pre_box">Term: </div><div class="entry"><?php echo get_post_meta($post->ID, $key, true); ?></div><?php endif; ?>`
Thomas
The text/variable is getting displayed whether or not the variable is set.
Thomas
+1  A: 

If isset() does not work, try empty() instead:

<?php if( !empty( $key ) ): ?> 
    <div class="pre_box">Term: </div>
    <div class="entry">
         <?php echo get_post_meta($post->ID, $key, true); ?>
    </div> 
<?php endif; ?>

isset() will deliver TRUE if the value is set and has a value different from NULL.

empty() instead will deliver TRUE (hence !empty() results in FALSE) for:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

I assume your $key is set but with an empty string. Thus, empty() is the way to go here.

Felix Kling
I just updated my original post.
Thomas
@Thomas : Ok I see now. Of course, if you set `$key` beforehand, it will never be empty ;)
Felix Kling
+1  A: 
<?php 
    $post_meta = get_post_meta($post->ID, 'term', true);
    if (!empty($post_meta)) {
?>
        <div class="pre_box">Term: </div>
        <div class="entry"><?php echo $post_meta; ?></div>
<?php
    }
?>
Casey Hope
Bravo Cobra Commander.
Thomas
A: 

Well they way your code is above, $key will never be empty, thus the pre_box will always be displayed. You're setting $key = 'term', which gives it a value so !empty($key) or isset($key) will always be true.

Casey's solution should give you the result you're going for.

Scott Christopherson