Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Is there a plugin for this? Has anyone done it before?

share|improve this question

3 Answers

up vote 2 down vote accepted

I use the Auto Post Thumbnail plugin for doing just that on this site and it works fine. First image in a post becomes the featured image every time.

share|improve this answer

You may find the answer in this tutorial : How to Set a Default Fallback Image for WordPress Post Thumbnails

Add this in functions.php in your theme folder :

add_theme_support( 'post-thumbnails' );

function myprefix_main_image() {
    $attachments = get_children( 'post_parent='.$post->ID.'&post_type=attachment&post_mime_type=image&order=desc' );
    if( $attachments ) {
        $keys = array_reverse( $attachments );
        set_post_thumbnail( $post->ID, $keys[0]->ID );
    }; 
}

And this in your template, where you want to show the post image :

<?php if ( (function_exists( 'has_post_thumbnail') ) && ( has_post_thumbnail() ) ) {
  echo get_the_post_thumbnail( $post->ID );
} else {
   myprefix_main_image();
   echo get_the_post_thumbnail( $post->ID );
} ?>

EDIT : much better, thanks Chip Bennett

share|improve this answer
Two comments: 1) function main_image() needs to be prefixed appropriately; the name is too generic. 2) The function would be so much better if it incorporated a set_post_thumbnail() on whatever image it returns. – Chip Bennett Jul 22 '11 at 13:39
You're right Chip, the code was ugly, I had copy-pasted it from the tutorial. I updated it, now it sets the first content image as a post_thumbnail. – mike23 Jul 22 '11 at 14:02
Just looking at the code, do you need to return the Post Thumbnail when you're done? – Chip Bennett Jul 22 '11 at 14:08
Updated, the thumbnail is echoed after our function is called. – mike23 Jul 22 '11 at 14:22

Get The Image is great plugin for related functionality. You will need to configure funciton call a bit, but it will be able both to scan for image and save it into thumbnail for you. Was writing quickly and messed up a bit. What it can do is save found image into custom field (which might or might not be what you want). If you want to actually make featured image out of it - that is going to be considerably more complex.

share|improve this answer
i think i had some code once that scanned through the post and picked up any images, but get the image does more and is neater. if i recall, it doesn't scan by default, but it is one of the many options available. – helgatheviking Jul 22 '11 at 15:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.