YouThis gets asked a lot so lets try and fully explain it.
We can writesimply wrap it like this: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; ?>
OrBut that is ugly, and why do 2 queries when you can store it for more convenience and cleaner code indo one instead? So we will put the post_meta value into a variable like, like $film_genre = get_post_meta($post->ID, 'genre', true;
and then just write if($film_genre) do something;
.
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';
}
An even better way would beFurthermore 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 use make sure using get_post_custom!empty
, that way( 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 usingexample uses 7 meta boxes, let just 1use one query function call instead of 7to 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. Sometimes it is better to check if the value is empty using !empty
or some people like !==""