Develop

WordPress: Display Post Meta if it Has a Value

So, you want to return some values from your WordPress Custom Fields (post_meta) on condition those values exist, eh? Don’t worry…it’s easy!

I’m assuming you have already figured out how to return your Custom Field values, but in case you haven’t, here is some general information from the codex:

    $meta_values = get_post_meta($post_id, $key, $single);

This function returns the values of the custom fields with the specified key from the specified post. (Source: Function Reference/get post meta)

Example

Website Magic

[ fig 1.0 magic ]

I’m going to use a real-world example based on this site…

I have three areas of service for the items in my portfolio: Design, Development and Deployment. Each of these three service areas exists as a WYSIWYG Custom Field in my Portfolio Custom Post Type. However, I haven’t performed all of those services for each of my clients, so I don’t want the headings and related icons spitting out on every Project Page without content…that just wouldn’t make sense!

Let’s just use a simple conditional to decide whether or not a service item should be displayed on the page: if a WYSIWYG Custom Field has a value (if there is text sitting in it), then show it. Simple.

Solution

I’m just going to show you an example of the WYSIWYG for my Design work, all the others would be set up the same way. First, let’s get the value from the post meta:

    $my_post_meta = get_post_meta($post->ID, 'Design-Service', true);

Next, we will write the condition on whether or not the elements related to Design Service should show on the page:

    <?php $my_post_meta = get_post_meta($post->ID, 'Design-Service', true); ?>
    <?php if ( ! empty ( $my_post_meta ) ) { ?>
        <div class="service group">
             <div class="icon">
                 <img src="<?php bloginfo('template_directory'); ?>/images/hex-design.png" alt="Web Design Service" />
	     </div>
	     <div class="info group">
	        <h3>Design</h3>
                <?php echo wpautop($my_post_meta); ?>
             </div>
         </div>
    <?php } ?>

Explanation

The key here is this:  if ( ! empty ( $my_post_meta ) ) { OUR CONDITIONAL STUFF HERE }. The if ( ! empty ) is essentially saying “if this is NOT empty, then do everything inside the braces, do { OUR STUFF }.

In my case, “our stuff” is a <div> that wraps my service item, a service-specific icon on the left with the service title <h3> and service description on the right…all of which would be hidden if there were no value inside of my Custom Field.

Now, go get conditional with that awesome content of yours!

{ 29 Comments }

  1. Mohamed

    Thank you, just got my post meta working. :)

  2. Tom

    and even 2 years after publishing and still helpful! Thanks!

{ Respond }

Leave a response