Using custom fields in WordPress posts

Probably everyone has seen (and ignored) the Custom Fields (see screenshot) in WordPress when writing a post, just because the results are unknown when filling something in these fields, and one is afraid of breaking something, or, since they’re not needed anyway, why not ignore them forever.

customfields1.png

Well, the potential uses are unlimited, so I’m going to describe some of them.

In most examples about the Custom Fields, ‘mood’ is mentioned. One could fill the Custom Field with his or her mood, and this mood could then somehow be shown on ones post. So lets create a mood.

If you’ve never used Custom Fields in your blog (and you probably haven’t, or you would not be reading this article), then the input screen looks like the one above. After filling the input fields, the screen looks like this:

customfields2.png

And after pressing ‘Add Custom Field’ like this:

customfields3.png

Now comes cool part number 1: if you press the publish button, the input screen changes somewhat:

customfields4.png

The Custom Field we just created remained the same, however the ‘add new custom field’ entry contains a pulldown. If you pull it down, then you will see all Custom Fields created in this WordPress installation, in this case only ‘mood’. WordPress now knows about this Custom Field and it will present the pulldown in all posts and pages you want to create (or modify, of course). If you want to add another Custom Field (other than ‘mood’, for instance ‘hair color’ – my wife changes the color of her hair more often than other people change underwear), then you click the ‘enter new’ link. Again after publishing this Custom Field will be available in the pulldown.

If you already published the post you just modified (or created) and preview it on your site, you’ll see no difference whatsoever. WordPress internally knows about your Custom Field, but doesn’t know what to do with it.

I will change the Default Theme of WordPress to show the usage, but of course you can embed this in any theme you like. The file I’ll be changing is single.php, and I’m going to put the mood just above the meta information.

The part in single.php looks like this:

 
<p class="postmetadata alt">...</p>

and the post I just modified looks like this:

customfields5.png

The first thing to do is to pull the Custom Field from the post. The function for doing this is get_post_meta(). This function will need three parameters: the ID of the post, the name of the Custom Field (in our case ‘mood’ – or ‘hair color’ if you’re my wife) and a boolean value, being true of false. The last parameter depends on whether get_post_meta() has to read several Custom Fields with the same name (false) or should stop at the first it encounters (true). Since we have (or want) only one mood (or hair color) this parameter will be true.

 
< ?php
  $mood=get_post_meta($post->ID, 'mood', true);
?>
 
<p class="mood">< ?php echo "Today, I'm feeling " .$mood; ?></p>
 
<p class="postmetadata alt">...</p>

What happens here: I’ve created a variable $mood, which will hold the value for Custom Field ‘mood’, which it will get from the current post ID ($post->ID). It will stop searching for ‘mood’, once it finds the first (true).

Next I echo it to the screen, preceded by “Today, I’m feeling “. The class is for styling, which I will not be doing here.

The post looks now like this:

customfield6.png

I could have used the following construction directly:

<p class="mood">< ?php echo "Today, I'm feeling " . get_post_meta($post->ID, 'mood', true); ?></p>

but then we have a problem with posts that don’t have a Custom Field ‘mood’ configured (which is the case for all other posts I have). Take a look at another post:

customfields7.png

That doesn’t look very pretty, does it? What we want to do is to create a default value, for the cases we didn’t define a mood we’re in.

< ?php
  $mood=get_post_meta($post->ID, 'mood', true);
  if ($mood == "") {
    $mood="unwilling to tell";
  }
?>
 
<p class="mood">< ?php echo "Today, I'm feeling " .$mood; ?></p>

customfields8.png

Looks better, doesn’t it. So now go ahead and give all your posts a ‘mood’ Custom Field.

That wasn’t too hard, now was it?

Some advanced uses

Earlier I wrote about the three parameters get_post_meta() takes, the ID of the post, the name of the Custom Field, and either true (for one value) or false (for multiple values). In case of ‘false’ the values will be put in an array.

Suppose we wanted a list with people we want to thank for their contribution below every post. This list can consist of zero, one or more people. First we add the Custom Fields to the post:

customfields9.png

And then add the code to single.php, just below the ‘mood-code’.

< ?php
$thanks = get_post_meta($post->ID, 'thanks', false);
 
if ($thanks) {
  echo "<h3>Special thanks to:</h3>\n<ul>";
  foreach ($thanks as $person) {
    echo "<li>".$person."</li>";
  }
  echo "</ul>";
}
?>

First we fill the array $thanks with all values (false) we find for ‘thanks’ from the current post. If the array contains no data, it’ll ignore the following part completely, and will not display anything.

If however the array contains some data, then it’ll display a title called ‘Special thanks to:’ and will query the array for every value and create an unordered list of it. This is how it looks in the default theme (of course you can add all kinds of formatting to it, you could present it in a table, or all names after another separated by commas, whatever you like):

customfields10.png

These Custom Fields can really hold any value you like. You could have it hold urls to images, prices for your products, paths to local resources for your products.

Suppose you wanted to create a product page that holds a product you want to sell, and it could contain zero, one or more images.
To display each image, you will need a path for the thumbnail, a path for the full size picture, and a title.

You could decide to create three Custom Fields for each image, but that would be a bit cumbersome, and probably overdone. So we don’t do that, but create just one Custom Field for each image, and put the values after another, with a separator we choose. In this case we will use the vertical bar (|).

Our ‘image’ Custom Field will hold the following value:

product1-thumb.jpg|product1.jpg|Very nice product

The code for this would be:

< ?php
  $images = get_post_meta($post->ID, 'image', false);
 
  if ($images) {
    echo "<h3>Pictures</h3>";
 
    foreach ($images as $image) {
 
      $fullValue = explode ("|", $image);
 
      $thumbPath = $fullValue[0];
      $fullsizePath = $fullValue[1];
      $description = $fullValue[2];
 
      $fullsizePath = "/wp-content/media/store/" . $fullsizePath;
      $thumbPath = "/wp-content/media/store/" . $thumbPath;
 
      echo "<a href='$fullsizePath' title='$description'><img src='$thumbPath' alt='$description' class='product-thumb' /></a>";
 
    }
  }
?>

The explode function extracts the three values (separated by the vertical bar) into an array $fullValue, which then can be used to extract the individual values. The ultimate goal is to display the thumbnail, and to make it clickable to show the full size image. The description (‘Very nice product’) is used as title for the link and as alternate text for the thumbnail.

That’s all for now. Happy Custom Field.

This entry was posted on Monday, September 28th, 2009 at 8:11 pm and is filed under webpublishing. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

26 Comments to Using custom fields in WordPress posts

  • [...] See the original post: Using custom fields in WordPress posts [...]

    • Phyllis Erck says:

      Thanks for explaining Custom fields. I’ve been wondering what they could offer. You did a great job with your example code and all. I completely get all the coding. Only thing I didn’t get is, how you actually get the code into your post. Is single.php an example php file or does it have some significant purpose to insert something into a post?

      • @Phyllis,

        Single.php indeed is just an example. Actually you can insert custom fields anywhere where you do something with posts or pages, like in search.php, index.php, page.php. One restriction though: since you always have to refer to a postID, its best to use custom fields in the loop.

        But if you know an ID, you could use them outside the loop.

  • [...] the previous article I showed how to create Custom Fields, and how to use them. I won’t go into the creating part [...]

  • Polprav says:

    Hello from Russia!
    Can I quote a post in your blog with the link to you?

  • [...] Custom Fields may come in handy if you wanted to add something to your post, but their content is always outside the actual content of a post (although inside the loop). [...]

  • Norbert says:

    Hi Peter,
    thank you for the nice tut. and the good examples.

  • [...] Custom Fields as well. You might want to read up on Custom Fields in my previous articles (”Using custom fields in WordPress posts” and “Example uses of custom fields in [...]

  • Bruno says:

    Thanks for the great tutorial.

    In the exemple with arrays, how can I display the results in ordered list?

    Thanks again, Bruno.

    • Just change the ul into ol:

      <?php
      $thanks = get_post_meta($post->ID, ‘thanks’, false);

      if ($thanks) {
      echo “<h3>Special thanks to:</h3>\n<ol>”;
      foreach ($thanks as $person) {
      echo “<li>”.$person.”</li>”;
      }
      echo “</ol>”;
      }
      ?>

  • arturo says:

    Very useful article.

    I used the above code to output something like this: field1, field2, field3
    Problem is I get: field1, field2, field3, (notice the last comma)

    Can this be eliminated?

    • Hi Arturo,

      There are several solutions to this problem:

      First of all, you could display the list as an unordered list (like in the example)m and style the list via css:

      (enclose the unordered list with <div id=”inline-list”>)

      #inline-list ul, #inline-list li {
      display: inline;
      margin: 0;
      padding: 0;
      }

      #inline-list-gen ul li:after {
      content: “, “;
      }

      #inline-list-gen ul li.last:after {
      content: ” “;
      }

      The advandage is that it’s still a list (for screen readers, for instance), but the disadvantage is thet these pseudo elements don’t work in every browser. Maybe some javascript could solve that problem (I do not know of one, google is your friend).

      I suspect however that you’ve abandoned the unordered list alltogether, so you would have to detect when the list ends. One possible solution would be this:

      $thanks = get_post_meta($post->ID, ‘thanks’, false);

      if ($thanks) {
      $counter=1;
      foreach ($thanks as $person) {
      if ($counter > 1) echo “, “;
      echo $person;
      $counter++;
      }
      }

      The trick here is to display the comma in front of the field, but not before the first one.

  • Darren says:

    Hello,

    This is great. I’m definitely bookmarking this page. I am using custom fields to pull in an image for my posts for a site I’m developing. I really like the code you have for displaying alternate text if there is no value found for a custom field. However, I would like to display a placeholder image instead of “dummy text”. I would like to use a ‘template_directory’ php link if possible but if I have to use an absolute URL that’s fine too.

    How would I do that?

    • You could write something like this:

      $thumbPath = get_post_meta($post->ID, 'thumbnail', true);

      if ($thumbPath == "") {
      $thumbPath = "comingsoon.png";
      }

      $thumbPath = "/wp-content/media/store/" . $thumbPath;

      I would keep the images out of the template directory, but that’s just my opinion.

      • Darren says:

        Sorry this is not really working for me. I’m pretty new to php. I think not all the characters are showing up in your example. I need to know how to actually call the image from the custom field when there is an image as well. I had it working but not in IE and then i lost everything I did.

        How does this work without img src= or an echo?

        • The code indeed wasn’t complete:

          The example above should be between php tags (<?php .. ?>)

          and then:

          <img src="<?php echo $thumbPath ?>" alt="" />

          The example was just to show how you could add a picture to an empty (or non existing) custom field

  • Darren says:

    Yay! Appears to be working in IE6 even. So, the image from the custom field gets pulled in as it should. If there is no value(image in this case) for that field, a placeholder image is inserted. Thanks again!

  • Wendi says:

    Is it also possible to make the condition the posts’ category? Maybe something like this (what not really works…)

    ID, ‘Updated on’, true);
    ?>

  • Wendi says:

    [code]ID, 'Updated on', true);
    ?>

    [/code]

  • Wendi says:

    great, works good…

  • Wendi says:

    Another try

    ID, ‘Updated on’, true);
    ? >

  • Wendi says:

    php
    if ( is_category(’29′) ) {
    $updatedon=get_post_meta($post->ID, ‘Updated on’, true);
    >

    php } else {
    }
    >

  • Wendi says:

    I give up. Thanks for you help.

  • venk says:

    really useful .. thanks for the lesson on how to control the display of custom field arrays. ace!

  • Mike Carter says:

    Great tutorial. Learned a lot — a way to put custom fields, same key, different values, into an array and display and one key with several values with delimiter.

    I’m weak in PHP in Visual Basic, you can put in an index variable rather than giving each a separate variable as above –> $fullValue[0]; $fullValue[1]; $fullValue[2]. And echoing these the same way, one variable per index number. It’s really inefficient. What if there were 30 Values? Yikes!

    You don’t have to show me how. I can figure it out if possible. Just, please same me some hours and say, CAN’T use variables as index number or Sure you can. :)

    Thanks, Mike

  • Leave a Reply

    Spam Protection by WP-SpamFree