Learning never exhausts the mind
Home >  Web Design > WordPress > Using WordPress Custom Fields

Published 20th April 2009 by

One of the many features of Wordpress you may have noticed whilst writing posts is the Custom Fields section that appears at the bottom of the new post screen. This is a very powerful feature allowing additional information to be attached to a post.
Creating Your First Website Series
  1. What are the types of website available
  2. Introduction to Web Hosting
  3. Registering Domain Names and Configuration
  4. Installing Wordpress
  5. Setting Up New WordPress Site
  6. How To Install WordPress Themes and Plugins
  7. Using WordPress Custom Fields
  8. Creating WordPress Themes
  9. Create Custom WordPress Shortcodes
  10. Creating WordPress Widgets
  11. WordPress Security 101
  12. 10 Essential WordPress Plugins for 2018
  13. 12 Best Free SEO Plugins and Tools

WordPress Custom Fields are a method of storing information about a post, but not contained within the post itself (similar to categories and date stamp).

Wordpress Custom Fields

Wordpress Custom Fields

Custom fields have a name and a value. WordPress remembers previously used field names and can be selected in the drop down list. You can also create a new field by typing the name into the text box provided. The "value" text area can contain any data you wish, from a single number or string to a whole paragraph or comma separated list.

In this article, I will show you how I use custom fields on my blog to show image thumbnails on some posts.

Create or Modify an existing post

Create a new post as you would normally, or modify an existing post, scroll down to the bottom and find "Custom Fields". You may have to click on the + symbol to expand the full contents.

Create a new field called "pictures", and enter a comma-separated list of URL's. For this example I will use "/images/icons/icon_lonewolf.jpg,/images/icons/icon_question.jpg". You will need to change these to images that exist on your website.

When you click on Add your new field will appear above and flash yellow. If it flashes red then there was some problem and an error will be displayed.

Save your post and view it, notice there is no mention of the custom field. That is because we need to tell WordPress what to do with the data before it is shown.

Modify your Theme

Now you need to modify your theme to process your custom fields.

In index.php (or any other file containing "the loop") we will retrieve the custom field and process it. I will use the default themes index.php as the example here.

"The Loop" in the default theme.

  while (have_posts()) : the_post(); ?>
    <div class=&quot;post&quot; id=&quot;post-&lt;?php the_ID(); ?&gt;&quot;&gt;
      &lt;h2&gt;&lt;a href=&quot;&lt;?php the_permalink() ?&gt;&quot; rel=&quot;bookmark&quot; title=&quot;Permanent Link to &lt;?php the_title_attribute(); ?&gt;&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;
      &lt;small&gt;&lt;?php the_time('F jS, Y') ?&gt; &lt;!-- by &lt;?php the_author() ?&gt; --&gt;&lt;/small&gt;&lt;br/&gt;&lt;br/&gt;
      &lt;div class=&quot;entry&quot;&gt;  
        &lt;?php the_content('Read the rest of this entry &gt;'); ?&gt;
      &lt;p class=&quot;postmetadata&quot;&gt;&lt;?php the_tags('Tags: ', ', ', '&lt;br /&gt;'); ?&gt; Posted in &lt;?php the_category(', ') ?&gt; | &lt;?php edit_post_link('Edit', '', ' | '); ?&gt;  &lt;?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?&gt;&lt;/p&gt;
  &lt;?php endwhile; 

Let's get the value of our field. Before the div containing the "rest of the entry" tag, add these lines:

      $pictures = get_post_meta($post->ID, "pictures", true);
      echo $pictures;

The first line will get the custom field called "pictures" for the current post as indicated by $post->ID You can change this id to any post number to get the custom field for that post. The second line simply outputs it to the screen. When you view your post now you should get back the value of your custom field you entered previously.

Now we need to do something useful with this custom field so let's add a few more lines to parse and output the images. Your finished script should look like this:

      $pictures = get_post_meta($post->ID, "pictures", true);
      //check that we have a custom field
      if ($pictures != "")
        // Separate our comma separated list into an array
        $pictures = explode(",", $pictures);
        //loop through our new array
        foreach ($pictures as $picture)
          echo "<img src='" . $picture . "' />";

After retrieving the custom field, we need to check that we have some data otherwise posts without images will have script errors in them. Next, we use the explode function to split out a comma separated list into an array of strings, then loop through all the array items in a foreach loop, outputting the picture to the browser in an img tag.

If all goes well you will now have two images in your post.

Clickable thumbnails from WordPress uploads

WordPress provides the ability to upload images and automatically generate thumbnails. There is a section where you can insert thumbnails or links into the body of the post. One of my clients did not wish to have the image code within the body but in a separate section. He also wanted to prevent images from showing in the RSS feeds. WordPress does not know what uploaded files are associated with a particular post, and you may wish to include attachments from another post, so the above method has been used and modified so that a given set of uploaded images can be displayed per post.

This code snippet assumes that images are uploaded using the standard file uploader.

When a file is uploaded, click on the edit link and you will see the URL listed in a read-only text box. We are interested in the last part of the URL, ignoring the static, so copy everything after uploads (e.g. "2008/01/my-sample-image.jpg")

Copy and paste this value from the URL field into a custom field called "pictures", if there is more than one image you wish to show, repeat the steps for each image and separate them with a comma. They should all be contained within the one picture custom field.

You can also use the "browse all" tab go through all uploaded images from the past. The code within the WordPress theme template should go like this within the loop:

  $pictures = get_post_meta($post->ID, "picture", true);
  if ($pictures != "")
    $pictures = explode(",", $pictures);
    foreach ($pictures as $picture)
      // convert image.jpg to image.thumbnail.jpg
      $thumbnail = str_replace(".jpg", ".thumbnail.jpg", $picture);
      // output a thumbnail linked to the large image 
      echo '<a href="/content/uploads/'.$thumbnail.'"><img src="'.$thumbnail.'"></a>';

Obviously, this code needs to be changed for your needs/template and the image tag needs width, height and alt tags in order to be W3C compliant but this should give you a head start.

How it works on my blog

Using a recent blog post about our new kitten as an example, the custom field holds the values:


The images and thumbnails have been uploaded onto my servers file system and the photograph details are stored within a database. The custom fields are then parsed by the following code:

    $images = get_post_meta($post->ID, "pictures", true);
    $count = 0;
    if (strlen($images) >0)
      echo "<p>&amp;nbsp;</p><span style="padding-left:8px; font-size:80%">Attached Thumbnails:</span><br/><div class=&quot;box&quot;&gt;&quot;;
      $images = explode(&quot;,&quot;,$images);
      foreach($images as $image)
        $query = "SELECT * FROM XXXXXXXX WHERE XXXXXXXX = '$image' LIMIT 0,1";
        $result = executeQuery($query,"XXXXXXXXXX");
        $title = $nt[photoTitle];
        $thumb = $nt[thumbnail];
        echo '<a href="/pictures/'.$image.'/"><img src="/' . $thumb . '" alt="' . $title . '" title="' . $title . '" class="thumbnail" /></a>';
        // 4 images per row
        if ($count == 4)
          echo "<br/>";
          $count = 0;
      echo "</div>";

I am using a custom executeQuery function which performs some validation, error trapping and reporting, but it can easily be changed for $wpdb database calls. I have also obscured the database and table names for security reasons.

The final result looks like this:

Hopefully, this has given you an insight into WordPress custom fields and how powerful they are. Their use is (mainly) limited by your imagination. Get creative and start using your new custom fields!

Tutorial Series

This post is part of the series Creating Your First Website. Use the links below to advance to the next tutorial in the couse, or go back and see the previous in the tutorial series.

11 thoughts on “Using WordPress Custom Fields
  • Fask
    7th October 2011 at 12:00 am


    it's possible, converts the linebreaks to html’s <br /> tag using PHP’s nl2br() function. We then create an array with the explode() function using the <br /> tag as the separator of the different lines of data?

    (sorry for my english)

  • Rotten Elf
    22nd February 2011 at 12:00 am

    I'm looking to make the display of my custom fields a little bit more aesthetically appealing to users. I would like to enclose the displayed custom fields' values within a box of some sort, or even have them appear atop an image. Does anyone know how to do this, or even point me in the right direction. I'm working on a directory and have taken the daunting task of using wordpress as the CMS, rather than purchasing an ugly directory script for the project. I would like to have the custom fields (which are the address, phone, city, state, etc.) appear a little more organized than the current ordered list that I've created. Any ideas????

  • Edward Palomo
    18th June 2009 at 12:00 am

    I'm planning to use WordPress as CMS to our organization's website...nice tut here...

  • 6th May 2009 at 12:00 am

    Just wanted to say thanks for the well-written post. I was looking for info on customizing the display of custom fields in WordPress and the examples in your post worked great! Wow, custom fields are really useful!

  • 4th November 2008 at 12:00 am

    I've read at least 6 other articles about custom fields. Including all the documentation at wordpress.org.

    You're a king among men.

  • 17th October 2008 at 12:00 am

    In you code example box, which one is the code that will display the custom box?

  • Kiten
    5th October 2008 at 12:00 am

    Great post, i use this field tip more often  :) 

  • 6th June 2008 at 12:00 am

    Thanks for great post!

    I need some help with the captions of the photos though. Would it be possible to add separate captions for the separate photos? How will i go about doing this (first-time custom fields user  ;-) 


  • mike
    14th May 2008 at 12:00 am

    hey there - great post! i was wondering how to go about linking that thumbnail to a different link, not the link to the enlarged picture. i&squot;m assuming, you&squot;d have to create another custom field to enter that specific url, which will tie it to the thumbnail, but that&squot;s just my best guess. would you be able to assist?

  • 7th February 2008 at 12:00 am

    Wow, this post is cool. I was thinking to customized my admin page php so that i can add a pic along with the post and i got the answer on this post. with the custom field section and the script you provided i can fully customize adding pics with the post plus i can position where to put the image where i exactly want. Thank for this post. This helped a newbie like me a lot.

  • 19th January 2008 at 12:00 am

    Hi thanks for posting this. Its exactly what Im looking to do. Im just not getting the last part, Im not so strong in PHP.

    Are the thumbnail images created automatically here?

    I would appreciate if you could explain the last bit in more detail. If you don't want to do this in your comment section I would be happy to receive an email from you.

    Thanks anyway this will get me startet.


Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.