Web Design that taps into the haromny and vision of your dreams.

Using WordPress Custom Fields

How to use WordPress Custom Fields

Written By on in PHP

1,411 words, estimated reading time 7 minutes.

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. How To Create Wordpress Widgets
  10. 10 Essential WordPress Plugins for 2008
  11. WordPress Security 101

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.

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

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

<?php
      $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:

<?php
      $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:

 
<?php
  $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:

pets/img_3832,pets/img_3886,pets/img_3894

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> </p><span style="padding-left:8px; font-size:80%">Attached Thumbnails:</span><br/><div class="box">";
      $images = explode(",",$images);
      foreach($images as $image)
      {
        $query = "SELECT * FROM XXXXXXXX WHERE XXXXXXXX = '$image' LIMIT 0,1";
        $result = executeQuery($query,"XXXXXXXXXX");
        $nt=mysql_fetch_array($result); 
        $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;
        }
        else
        {
          $count++;
        }
      }
      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!

Last updated on: Wednesday 21st June 2017

 

Comments
Fask

Fask

Hi,

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)

Reply to Fask
Rotten Elf

Rotten Elf

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????

Reply to Rotten Elf
Edward Palomo

Edward Palomo

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

Reply to Edward Palomo
Jordan

Jordan

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!

Reply to Jordan
Rodney

Rodney

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

You're a king among men.

Reply to Rodney
tyler

tyler

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

Reply to tyler
Kiten

Kiten

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

Reply to Kiten
Iaan

Iaan

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 ;-)

Thanks!

Reply to Iaan
mike

mike

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?

Reply to mike
Ross

Ross

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.

Reply to Ross
Kasper

Kasper

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.

Reply to Kasper

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me