WordPress: display images from custom fields

A couple of weeks ago I finished a WordPress project which consists of a jQuery slot machine product slideshow. The problem with this plugin was to allow the administrator to insert all the required images and captions in order to make the slideshow work. For that reason, I used WordPress custom fields. The tricky part is to fetch the images attached via custom fields. Let's see how.

When you use an image through a custom field, WordPress considers the image as a post attachment. For that reason, you have to use the wp_get_attachment_image_src() function:

$id = get_the_ID();
$image1 = wp_get_attachment_image_src(get_post_meta($id, 'image_1', true));
$image2 = wp_get_attachment_image_src(get_post_meta($id, 'image_2', true));
$image3 = wp_get_attachment_image_src(get_post_meta($id, 'image_3', true));

The aforementioned function returns an array containing:

  • [0] => url
  • [1] => width
  • [2] => height

Therefore, to display an image you have to write the following:

$image_1 = '<img src="' . $image1[0] . '"/>';
echo $image_1;

Further, you have to make the get_post_meta() function to return a string (not an array) by setting its third parameter to true.

One thought on “WordPress: display images from custom fields”

Leave a Reply

Note: Only a member of this blog may post a comment.