March 28, 2010

One of the best ways to liven up a blog, and something that most of the premium themes look to do by default, is adding images to your posts. The usual method of doing this is by adding the image URL via a custom field. But there is a better and more flexible way.

When you upload images in your post they are all added to the database. This makes it very easy to get a list of all the images attached to the post. In addition, WordPress has a built in function to retrieve the appropriate image size as well, meaning you can use a thumbnail on archive pages and a medium image on post pages without messing around with resizing images and adding multiple custom fields.

Below is a short function that I put together that does everything you need. Pop this in the functions.php file you will have an extra template tag: the_image.

function the_image($size = ‘medium’ , $class = ”){
global $post;

//setup the attachment array
$att_array = array(
‘post_parent’ => $post->ID,
‘post_type’ => ‘attachment’,
‘post_mime_type’ => ‘image’,
‘order_by’ => ‘menu_order’
);

//get the post attachments
$attachments = get_children($att_array);

//make sure there are attachments
if (is_array($attachments)){
//loop through them
foreach($attachments as $att){
//find the one we want based on its characteristics
if ( $att->menu_order == 0){
$image_src_array = wp_get_attachment_image_src($att->ID, $size);

//get url – 1 and 2 are the x and y dimensions
$url = $image_src_array[0];
$caption = $att->post_excerpt;
$image_html = ‘<img src=”%s” alt=”%s” />’;

//combine the data
$html = sprintf($image_html,$url,$caption,$class);

//echo the result
echo $html;
}
}
}

}

What this function does, in a nutshell, is to get a list of all the images attached to a post. It then finds the first image with a sort order of 0 and echoes the html to display it. By default all images have a sort order of zero unless you choose to reorder them. If you don’t make any changes then it will find the first image. If you reorder them using drag and drop the first image in the list will have an order of 1 and you would need to change it to 0.

To change the sort order of an image you need use the gallery tab:

Sort order panel

Using the tag

Using the tag is very simple. Insert the tag into the loop just above the the_content tag and select what size image you want, and what css class to attach to the image. I have used:

//in the single post page
<?php the_image(‘medium’,'post-image’); ?>
//in the index.php page
<?php the_image(‘thumbnail’,'post-thumb’); ?>

The result looks something like this (with a little CSS).

Index

Home page with thumbnail

Single

Single post page with medium image

Updated version

An updated version using many of the suggestions made in the comments is available in the easy peasy image suggestion roundup post.



Wordpress title showing space?
no comment on page 1371

Wordpress fun?
one comment on page 1376

Live blogging plugin?
4 comments on page 1258

Wordpress 3 admin speed up?
4 comments on page 1321

Framework photoshop?
3 comments on page 296

Fun wp plugins?
one comment on page 1376

Habari vs wordpress?
12 comments on page 440

Wp tags vs categories?
12 comments on page 7

Wordpress rss seo?
one comment on page 1361

Photo albums html5?
6 comments on page 1305

Wordpress chat?
no comment on page 1308

Wordpress exif data?
12 comments on page 230

Css sidear tab?
2 comments on page 336

Wordpress theme html5 blueprint?
6 comments on page 1305

Wordpress shortcode in plugin?
no comment on page 236

Html 50 photo album?
6 comments on page 1305

Get the post attachement?
24 comments on page 1065

Wordpress plugin development 30?
one comment on page 1373

Wordpress plugin development 30?
one comment on page 1373

Disqus formatting?
7 comments on page 1175

Html5 photoalbum?
6 comments on page 1305

Html5 photoalbum?
6 comments on page 1305

Wordpress fun?
one comment on page 1376

Fun wordpress plugins?
one comment on page 1376

Url shortener ideas?
4 comments on page 1190

Url shortener ideas?
4 comments on page 1190

Html 5 photo gallery?
6 comments on page 1305

Multiple post navigation?
no comment on page 1147

Html5 photo galleries?
6 comments on page 1305

Adding images to a wordpress 3 post?
24 comments on page 1065

Html5 photo gallery code?
6 comments on page 1305

Wordpress multiple blog master?
one comment on page 1376

Wordpress 3 tableprefix?
one comment on page 1376

Wordpress 3 tableprefix?
2 comments on page 1374

Using wordpress as a framework?
2 comments on page 335

Single post image size?
24 comments on page 1065

Get featured image src wordpress?
24 comments on page 1065

Disqus wordpress mu?
7 comments on page 1175

Image gallery html 5?
6 comments on page 1305

Wordpress theimage?
24 comments on page 1065

Wpgetattachmentimagesrc size?
24 comments on page 1065
  every 1741s, 1s ago, in 0.03s.
 __
(__)
   `
 Andrew Rickmann

That isn't part of the function but it is a very simply matter to add it in.

 __
(__)
   `
 Josh Byers

Great tutorial! This helps me so much!

Is it possible to call individual images attached to the post based on their sort order using this function?

The code might look like this:
<?php the_image('medium','post-image'); ?> Default, calls the image with the sort order of 0
<?php the_image('medium','post-image','1'); ?> Calls the image with the sort order of 1
<?php the_image('medium','post-image','2'); ?> Calls the image with the sort order of 2

And so on…

 __
(__)
   `
 tonygray216

Wow! That is great! You are da man…thanks for the quick turn around.

 __
(__)
   `
 Andrew Rickmann

Take a look at my next post Vivien. I have updated the function to do what you want:
http://www.wp-fun.co.uk/2009/01/10/easy-peasy-i...

 __
(__)
   `
 Andrew Rickmann

Tony, I have updated the code in my new post: http://www.wp-fun.co.uk/2009/01/10/easy-peasy-i...

I don't know much about thickbox so I have implemented the default, just as you have, and got the same results.

 __
(__)
   `
 inspirationbit

Thanks, Andrew. So basically, you're saying that I should leave the things as is on my blog: use a custom field to display the featured image and make this image available in RSS with the hook?

 __
(__)
   `
 Tony Gray

great! I'm looking forward to it. Maybe you will help me figure out why I'm seeing the close image instead of the text. You can see what i've done here. http://blog.tgrayimages.com/

 __
(__)
   `
 Andrew Rickmann

Hi Tony,

There is another way to do it which would be more flexible. Look out for the follow up post where I roll up the suggestions and I will include it there.

 __
(__)
   `
 Tony Gray

This will be one of the most useful tutorials in my toolbox. I can't tell you have much headache you have just saved me. I've been trying to teach my clients how to post images using the custom fields it and freaks them out. This is AWESOME. I made a couple of additions to your function. I wanted to be able to click on the image and show the large image in the jquery thickbox. Here is the modified code and all seems to be working great! I enqueued jquery and thickobx and then modified the anchor tag. Let me know if there is a better way.

Thanks for the code!


function tb_enqueue() {
wp_enqueue_script('jquery');
wp_enqueue_script('thickbox');
}
add_action('wp_head', 'tb_enqueue', 1);

function the_image($size = 'medium' , $class = ''){
global $post;

//setup the attachment array
$att_array = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order_by' => 'menu_order'
);

//get the post attachments
$attachments = get_children($att_array);

//make sure there are attachments
if (is_array($attachments)){
//loop through them
foreach($attachments as $att){
//find the one we want based on its characteristics
if ( $att->menu_order == 0){
$image_src_array = wp_get_attachment_image_src($att->ID, $size);
$image_src_array_large = wp_get_attachment_image_src($att->ID, "large");

//get url - 1 and 2 are the x and y dimensions
$url = $image_src_array[0];
$url_large = $image_src_array_large[0];
$caption = $att->post_excerpt;
$image_html = '<img src="%s" alt="%s" class="%s" />';

//combine the data
$html = sprintf($image_html,$url_large,$url,$caption,$class);

//echo the result
echo $html;
}
}
}
}

 __
(__)
   `
 Ben Whitehouse

Thanks Andrew. I did a little dance and hacked something together that now works. Thanks!

 __
(__)
   `
 Andrew Rickmann

Ben, the sprintf function replaces the instances of %s in the first of the arguments with the text in subsequent arguments, so sprintf('','Link','Title') would replace the first %s with link and the second with title.

Doing what you want would be easy. You need to wrap the sprintf statement in an if…else block that checks if you have included 1 or not. If it has then you use a version with the link html in it, otherwise you use the version without (the one that is there already).

I think the permalink is in $post->permalink.

 __
(__)
   `
 Ben Whitehouse

Okay, I tried to edit the fuction to do this, but I'm not entirely sure how you got the “%s” to do your bidding, so I'm going to ask, very nicely, for a little guidance. Is there a way I could roll in a link to the permalink using a third attribute in the function? like:

<?php the_image('medium','post-image','1'); ?>

where '1' is to add the permalink and '0″ is to not include it? My problem is I want to have the image link to the article, but thusfar I have to add it manually, regardless of if there is an image or not. Maybe I should just learn how to code :( I'm trying to figure it out on my own, but any advice would be greatly appreciated. thanks.

I am a baby. Great tutorial!

 __
(__)
   `
 Ben Whitehouse

Yes, Wordpress has by default 3 sizing options (thumbnail, medium, large) which can all be set in under the “Setting > Media” tab in your wordpress install.by selecting any of these options the tag will return the appropriate sized options. It will not scale an existing image to fit.

 __
(__)
   `
 ioni

Can be easily refined to de many things, but this is a very good one!
Certainly gonna use it!

 __
(__)
   `
 Ben Whitehouse

YOU ARE BRILLIANT! I was looking to use multiple image sizes on a web site I just launched last week (365inches.com) and let me tell you I looked and looked. In the end I came up with a REALLY convoluted solution. I need to recode my image calls pronto!

 __
(__)
   `
 links for 2009-01-09 | Svakodnevnica blog

[...] Post image the easy peasy way Insertacija slika u WP na laksi nacin (tags: wordpress) Podelite ovaj sadr

 __
(__)
   `
 cubus

Very nifty indeed.

To give even more flexibility with different image sizes you could consider to use the TimThumb PHP script in your function. It allows you to server-side resize images and cache them for future use. So basicly you can pick any size of image you like.

http://www.darrenhoyt.com/2008/04/02/timthumb-p...

 __
(__)
   `
 mkjones

Hey Andrew, would I be right in thinking that if I change:

function the_image($size = 'medium' , $class = ''){

to:

function the_image($size = 'thumbnail' , $class = ''){

I will get the smaller 'thumbnail' version of the uploaded image and not the downscaled 'medium'?

Thanks for a great tutorial :)

 __
(__)
   `
 Andrew Rickmann

Vivien, I would treat the feed image entirely separately by using a hook to add the image; i.e. use add_filter to filter the post_content. Within the function that it points to check if is_feed() is true and if so add the image where you need it.

Does that make sense? If not I will write a follow up.

 __
(__)
   `
 inspirationbit

thanks for sharing this, Andrew. It will come very handy for me in future.

I've got a question to you:
Right now on Inspiration Bit, I display the post's image in a separate DIV tag, that appears before the post's content. And alongside that image I display the post's metadata and title. Because of that specific layout, the only way I could figure out how to deal with the post's featured image is to have a custom field. It works fine, but then that image doesn't appear in RSS. So is there a way that I can have that image treated differently with CSS to fit with my layout and still show up in my post as the first image before text?

 __
(__)
   `
 WordPress Links – Week 2 2009 | WPStart.org – WordPress themes, plugins and news

[...] Post image the easy peasy way [...]

 __
(__)
   `
 Andrew Rickmann

WordPress calculates a large size as well so there would be three different sizes; all user selectable.

 __
(__)
   `
 Magnus

This is a very nifty function! It could be very valuable for us theme developers.

Only limitation is that you can't have many different sizes as magazine themes have. But two sizes should be good for most themes.

 __
(__)
   `
 Post Images The Easy Peasy Way — WPCandy — WordPress Themes, Plugins, Tips, and Tricks

[...] An interesting tutorial by Andrew Rickman on a great way to display uploaded images inside posts. [Link] [...]


0.02s