Associating an image with a post in WordPress

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.

Read More

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

Thanks in advance.

Related posts

Leave a Reply

4 comments

  1. 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.

  2. 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.

  3. 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.