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. Shafar

    1+ year old post and a life saver! Couldn’t understand other sites with more complicated explanations! Thanks! :)

    • Chris Perryman

      I agree! There are a lot of very complex solutions for this that was why I posted it here…so glad it helped :)

  2. Thanks for the info.

    I’m currently building travel guide directory site using a Premium Press directory theme and a custom child theme. I am at the point of customizing my listing pages. I think I can use this to achieve what I am looking for. For a listing such as a hotel I want to display icons in a row associated with each amenity offered by that hotel. During the listing submission process the amenities offered or identified through a check list. So to achieve this would I be able to use your code modified as?

    WiFi, true); ?>

    Thanks so much!

    • Chris Perryman

      Hi Mark,

      If your post meta has a key of “WiFi”, then yes you should be able to change that item in my code and then modify the HTML to suite your needs.

      You can set this method up for each of the checkbox items you want to display on condition.

  3. Ashraf

    I’m now building a custom theme for my portfolio website. On my landing/homepage I want to display from (another page’s custom field’s data – in which I wrote information about the title of service I offer. very strange but I can’t get this work. any idea?

    Thanks.

    • Chris Perryman

      You need to include the actual ID of the page that you’re trying to pull the custom field from. Let me know of you need more instructions.

    • Ashraf

      Thanks for replying. Here’s how my actual codes look like inside index.php:

      services i offer

      ID, ‘tagline’, true); ?>

      I have also tried to replace $post->ID with actual page’s id which is 18 without any luck.

      Please note, my theme currently only have the index.php page and I’m not calling get_header(); as header section is currently hardcoded in index.php page itself.

      I also went through wordpress codex which states following:

      “If you are using The Loop inside your own design (and your own design is not a template), set WP_USE_THEMES to false”

      not sure what is this for and does this mean anything to my case?

      Thanks again.

    • Ashraf

      I messed up pasting code here on comment. anyway, below is the code I am trying…

      http://tny.cz/a0f8a3bd

    • Chris Perryman

      Very odd. You would need to have:

      echo get_post_meta(18, 'services', true);

      I would suggest double checking the $key for spelling errors. I wouldn’t think that your header should effect this. I’m also assuming the rest of your theme (loops etc.) are working?

    • Ashraf

      Hmm, I only have index.php in my theme, no other page template. In wordpress Settings > Reading Settings front page display set to “Your latest post” – is this the reason ? Sorry I’m really starting off with wordpress. This may be stupid question.

    • Chris Perryman

      You are adding the code to index.php correct? Not to functions.php or any other file? It should still work…you don’t necessarily need any other template page other than index.php.

    • Ashraf

      Yes, adding the loop in index.php file not in functions.php. Anyway, I will search more to get solution. thanks a lot for your suggestions.

    • Chris Perryman

      From the admin area, if you are editing the page that has the meta value, and you click “view page”…can you see it displaying correctly there?

      And that would be using $post->ID.

    • Ashraf

      Nope, its returning a blank page (also source code has noting inside)

    • Chris Perryman

      Hmmm…it seems you may have an issue going on here. Your index.php should be able to display any page on your site. Do you have other files in your theme folder? Like page.php or single.php?

    • Ashraf

      well, my theme folder contains index.php, functions.php style.css and folders for img/css/js. Not using page/single.php yet. my index.php file is basically was a simple html webpage which I later converted into wordpress index.php file. I have already setup header section, empty body and footer section (I’m not calling these section from any files like, header.php or footer.php) those tags are still embedded inside same page.

      in the body container area, I’m trying to use the wp loop without luck. Other than that, I made a static page inside wordpress, titled it service and added a custom meta box for tagline. – I dont really want to show this page publicly other than pulling information to my theme’s landing page to display the service I am offering.

      Not yet sure what’s wrong I’m doing here.

      Thanks,

    • Chris Perryman

      I’m going to email you….let’s try and figure this out ;)

    • Ashraf

      Many many thanks for your suggestion to check the_title() and I figured that I was missing to close the ‘while’ loop.

      It was very nice of you to support me personally.

  4. Thanks , we are currently building a new site using WordPress Post Meta Data types and was looking for this solution.

    • Chris Perryman

      Glad to have helped! Good luck with the build :)

  5. what is params number 2 of function “get_post_meta” ?

    • Chris Perryman

      The second parameter is the $key for your meta value — or the “name” of that meta value. Depending on how you’ve setup your Custom Fields, you can find the $key/name in a couple of ways:

      1.) If you used the built in “Custom Fields” option that is native to WordPress the $key (or “name”) will be the value in the left column under the heading “Name”.

      2.) If you used a plugin like Advanced Custom Fields — you will need to look at the options where you setup the custom field. In that particular plugin, they $key (or “name”) is the value in the third column under the heading “Field Name”.

      I hope this answers your question!

{ Respond }

Leave a response