Leave a Reply

1 comment

  1. This gets asked a lot so lets try and fully explain it.

    We can simply wrap it in an if statement and echo the value, for example,

       <?php if ( get_post_meta($post->ID, 'genre', true) ) : ?>
         <?php echo get_post_meta($post->ID, 'genre, true) ?> ?>
       <?php endif; ?>
    

    But that is ugly, and why do 2 queries when you can do one instead? So we will put the post_meta value into a variable, like $film_genre = get_post_meta($post->ID, 'genre', true;.

    This would look like:

    $film_genre = get_post_meta($post->ID, 'genre', true);
    
      if ( $film_genre ) {
        echo 'something is here';
      }
      else {
        echo 'nothing is here';
      }
    

    Furthermore I find the function a little wonky in terms of checking whether it is empty or not so I add an additional check just to make sure using !empty ( this checks to see if the meta box value is NOT empty).

    That looks like:

     $film_genre = get_post_meta($post->ID, 'genre', true);
    
      if (!empty($film_genre)) {
        echo $film_genre;
      }
    

    But that’s not it! Since your example uses 7 meta boxes, let just use one query function to grab them all using get_post_custom. http://codex.wordpress.org/Function_Reference/get_post_custom

    That would look something like:

    $film_meta = get_post_custom( $post->ID );
    if ( $film_meta ) 
    { 
        echo $film_meta['genre'];
        echo $film_meta['rated'];
        echo $film_meta['releasedate'];
        echo $film_meta['runtime'];
        echo $film_meta['director'];
        echo $film_meta['cast'];
        echo $film_meta['grade'];
    }
    

    Now that is much better, it might look silly echo-ing tons of stuff in a row, but this is just an example, typically your adding some markup around the values or perhaps additional code, the important part is that your only using one function, and it is clean and easy to read/understand and output.

    ps. Also note the the 3rd parameter of get_post_meta set to “true” does not mean the value is intuitively true, but rather sets the result to a single value, and returns nothing if empty.