views:

524

answers:

4

Hi,

What's the best way to associate an image with a post in WordPress?

What I mean by that is when each post has a 'header' image which is not in the body of the post. You'd most likely use it to show a small image next to each post when they're listed somewhere.

I know you can use custom fields with posts, but are there any better ways of doing it?

Thanks in advance.

+1  A: 

Not really any better way than custom fields, although you could always write out a unique class name containing the post ID on the container div and add the images via CSS each time you add a post. You'd end with a potentially huge CSS file though so I'd go for custom fields myself.

sanchothefat
+1  A: 

If you go the custom field route - in your template code you can save the value of the custom field to a variable and then echo it out to your image.

<?php $post_image = get_post_meta($post->ID, post_image, true); ?>
<?php if( $post_image != "" && isset($post_image) ) : ?>
   <p><img src="<?php echo $post_image; ?>" alt="<?php echo $post_image; ?>" /></p>
<?php endif; ?>
<?php the_content('read more...'); ?>

The function the_content() may or may not be what you will end up using - for more control, you can try setting a new WP_Query() and then revamping the loop.

Tim Schoffelman
+1  A: 

If you want a different image per post then use Customs Fields as suggested before - the only problem with that will be that Custom Fields are text fields and so you will have to upload your image and then paste the filename into your Custom Field. You could use the normal Add Image facility in the main post entry form but that will break up your workflow a bit as you will have to: upload the image in main post form, copy image url from HTML of form, remove image from form, paste URL into a custom field.

A bit of a pain!

If you want to use an image per category. Say, for example, you have a thumbnail for news items and a thumbnail for tutorials and so on. You could edit your WP theme template, check the category inside The Loop and show the relevant image from there.

The first option is a bit of a pain and the second requires some PHP coding.

Steve Claridge
A: 

A good way of associating an image with a post is to call the first image attached to that post in your template file.

I've elaborated a bit in this thread:

http://stackoverflow.com/questions/682926/how-would-you-recommend-adding-an-image-as-a-custom-field-in-wordpress