0

I'm using the code below to display an image if the swap_select custom field value is true. If it's no it displays nothing. However when posts are first created no custom field exists. So what would the conditional be to account for no custom field at all and in that case display noithing?

<?php 
$swap_value = get_post_meta($post->ID, 'swap_select', true);
// check if the custom field has a value
if($swap_value!= 'no') {
  echo '<img class="" src="thumbs/speechbubble_pink.png"/>';
}
else{
}
?>

1 Answer 1

1

I prefer empty for this because it considers a lot of things to be "empty" besides just an empty string, and that is the behavior I usually want. Be aware of that though.

I am not 100% sure what you are doing but...

if( empty($swap_value) ) {
  // runs if no $swap_value, or an empty value
}
// OR
if( !empty($swap_value) ) {
  // runs if $swap_value is set to something
}

Reference the PHP Docs for exactly what empty considers "empty" or "not empty".

3
  • Hi, for the condition if !empty do I have to add && $swap_value =='no' to set a condition for no? I ask because now I have three conditions that I need to work with, empty, yes, no, and a third value
    – Anagio
    Jan 17, 2013 at 3:59
  • 1
    I'm sorry. I don't understand exactly what conditions you need to match, but you may need to add a third if or an if/else.
    – s_ha_dum
    Jan 17, 2013 at 4:57
  • I used if elseif else
    – Anagio
    Jan 17, 2013 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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