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 trying to call some hidden custom fields into a meta box. The custom fields are the same - a maximum of five named _link and five named _url, with sequential numbers following (eg _link3). However, if the user has only filled in one link when submitting the post, I don't want the empty fields to appear.

I have knocked up the following loop. In theory, it should do a get_post_meta for _link0, and if it isn't empty it should do the same for _url1, print the results, and advance the counter to process _link1/_url1. With _link0/_url0 contained in the database, those fields appear fine. What I'm finding is that because _link1/_url1 aren't in the database, the loop will print the first field correctly, followed by four more empty fields.

I'm stumped. I've seen posts that suggest using !empty($link) and found that while it prints the first fields fine, the second fields will cause a fatal error (maximum execution time exceeded) and stop the page from loading. My code is below - am I overlooking something simple?

$i = 0;
do {
       $link_key = '_link' . $i;
       $url_key = '_url' . $i;
       $link = get_post_meta($post->ID,$link_key,TRUE);
       if (isset($link)) {
          $url = get_post_meta($post->ID,$url_key,TRUE);
          include(MY_PLUGIN_FOLDER . 'links.php');
          $i++;
       } else { $i = 5;}
    } while ($i<=5);

links.php:

<div>Link Name: <input type="text" name="link<?php echo $i; ?>" id="link<?php echo $i; ?>" value="<?php echo $i; ?>" /> URL: <input type="text" name="url<?php echo $i; ?>" id="url<?php echo $i; ?>" value="<?php echo $i; ?>" /><input type="button" class="addnew" value="Add Link" /></div>
share|improve this question
    
add $link=''; before $link = get_post_meta($post->ID,$link_key,TRUE); to reset the $link value. –  Bainternet Feb 23 '11 at 23:28
    
get_post_meta is an empty string on fail, so technically that's still classed as being set(i think), switch to an empty conditional check instead, eg. if( !empty( $link ) ).. –  t31os Feb 24 '11 at 1:03
add comment

1 Answer

The get_post_meta function returns an empty string if the key has not yet been set. That means the unused fields are going to result in $link having a value of '', NOT a value of NULL.

The isset function returns TRUE if the variable exists and has value other than NULL. As $link is not NULL (it's ''), isset will return TRUE and your code will run.

Perhaps you should use empty instead of isset, although for some reason, I typically use the following:

if (isset($link) && $link != '')
share|improve this answer
add comment

Your Answer

 
discard

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