I’m using WordPress. I have a movie review website called Filmblurb. For my blog posts, I’m trying to create posts with different categories. Under the “Reviews” category, I have a “Details” box that serves as meta information for all my reviews.
The problem is when I try to create a post that has the category of “Features” or something else, that “Details” box still remains. Basically, I want to try to create a PHP if statement that will only return the following code sequence when I only write a “Reviews” post. I’m using the “get_post_meta();
” tag in WordPress to fill in this “Details” box for every “Reviews” post I write. A sample post can be found here.
<div class="box">
<div class="boxheader">Details</div>
<div class="text">
<h1>Genre</h1>
<p><?php echo get_post_meta($post->ID, 'genre', true); ?></p>
<h1>Rated</h1>
<p><?php echo get_post_meta($post->ID, 'rated', true); ?></p>
<h1>Release Date</h1>
<p><?php echo get_post_meta($post->ID, 'releasedate', true); ?></p>
<h1>Runtime</h1>
<p><?php echo get_post_meta($post->ID, 'runtime', true); ?></p>
<h1>Director</h1>
<p><?php echo get_post_meta($post->ID, 'director', true); ?></p>
<h1>Cast</h1>
<p><?php echo get_post_meta($post->ID, 'cast', true); ?></p>
<h1>Grade</h1>
<p><?php echo get_post_meta($post->ID, 'grade', true); ?></p>
</div>
Let me know if I need to explain more.
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,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:
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:
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_customThat would look something like:
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.