Custom Fields in Wordpress
This article covers what custom fields are and how to use them in your Wordpress blog.
One of the 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.
Custom fields are a method of storing information about a post, but not contained within the post itself (similar to categories and date stamp).
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 in 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>
<div class="entry">
<?php the_content('Read the rest of this entry »'); ?>
</div>
<p class="postmetadata"><?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?> <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?></p>
</div>
<?php endwhile;
?>
Lets 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 lets 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 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 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="/wp-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="http://lonewolf-online.net/pictures/'.$image.'/"><img src="http://lonewolf-online.net/' . $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:
Attached Thumbnails:
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!
Comments
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!
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.
















