Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I need to set a featured image for every post I publish. So, when a post is published/updated, the script would scan the post for the first image using a script like this:

   // Get URL of first image in a post
   function catch_that_image() {
   global $post, $posts;
   $first_img = '';
   ob_start();
   ob_end_clean();
   $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content,      $matches);
   $first_img = $matches [1] [0];

   // no image found display default image instead
   if(empty($first_img)){
   $first_img = "/images/default.jpg";
   }
   return $first_img;
   }

So, it would get that image and set it as a featured image for that post. If there is no image, then do nothing. I have looked into many scripts and plugins but none do it the way I am asking.

share|improve this question
add comment

2 Answers

This might work for you as well. It scans the post, then pulls in the image set as 'featured'. If that doesn't exist, it returns the first image attached to the post. If there isn't one, it looks for any image in the post; if that's not there, it grabs a YouTube screenshot. Put this in your theme's functions.php file:

// Note that your theme must support post thumbnails for this function to work. 
// If you are getting an error try adding add_theme_support('post-thumbnails'); to your functions. php file  
function vp_get_thumb_url($text, $size){
    global $post;
    $imageurl="";

    // Check to see which image is set as "Featured Image"
    $featuredimg = get_post_thumbnail_id($post->ID);
    // Get source for featured image
    $img_src = wp_get_attachment_image_src($featuredimg, $size);
    // Set $imageurl to Featured Image
    $imageurl=$img_src[0];

    // If there is no "Featured Image" set, move on and get the first image attached to the post
    if (!$imageurl) {
        // Extract the thumbnail from the first attached imaged
        $allimages =&get_children('post_type=attachment&post_mime_type=image&post_parent=' . $post->ID );

        foreach ($allimages as $img){
            $img_src = wp_get_attachment_image_src($img->ID, $size);
            break;
        }
        // Set $imageurl to first attached image
        $imageurl=$img_src[0];
    }

    // If there is no image attached to the post, look for anything that looks like an image and get that
    if (!$imageurl) {
        preg_match('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*)/i' ,  $text, $matches);
        $imageurl=$matches[1];
    }

    // If there's no image attached or inserted in the post, look for a YouTube video
    if (!$imageurl){
        // look for traditional youtube.com url from address bar
        preg_match("/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/watch(\?v\=|\/v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);
        $youtubeurl = $matches2[0];
        $videokey = $matches2[3];
    if (!$youtubeurl) {
        // look for youtu.be 'embed' url
        preg_match("/([a-zA-Z0-9\-\_]+\.|)youtu\.be\/([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);
        $youtubeurl = $matches2[0];
        $videokey = $matches2[2];
    }
    if ($youtubeurl)
        // Get the thumbnail YouTube automatically generates
        // '0' is the biggest version, use 1 2 or 3 for smaller versions
        $imageurl = "http://i.ytimg.com/vi/{$videokey}/0.jpg";
    }

    // Spit out the image path
    return $imageurl;
}

To display this in your theme files, first insert the following:

<?php
if (function_exists('vp_get_thumb_url')) {
                                // Set the desired image size. Swap out 'thumbnail' for 'medium', 'large', or custom size
                                $thumb=vp_get_thumb_url($post->post_content, 'large-feature'); 
                            }
?>

and somewhere after that, to display the actual image, in this case wrapped with a link to the post:

<?php if ($thumb!='') { ?>
                                        <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>" rel="bookmark"><img src="<?php echo $thumb; ?>" alt="<?php get_the_title(); ?>" /></a>
                                    <?php } ?>

Search Google on the vp_get_thumb_url function name for other articles on how to implement this. Best of luck!

share|improve this answer
    
Thank you SOO much for this answer! I love the YouTube support. Also, I enhanced it further by giving it defaults based on categories after the YouTube and a final "if all else fails" back-up default. Feel free to use it as you want: PasteBin: Image from Post (Featured, Attached, 1st Image, YouTube, Category Defaults, Backup-Default) –  joshmax Sep 14 '12 at 18:09
    
Thanks @joshmax! Glad it helped, and awesome additions to the function. I'll try it out when I'm back online. Thx again! –  Michelle Sep 16 '12 at 4:16
add comment

Use your function with these two function read the comments in the code to understand

/**
 * If the the image is an attachment we just set the id as the post thumbnail,
 * if not then we get the first image from the post content , upload it using media_sideload_image and then we set the thumbnail
 * 
 * @param (int) $post_id post id
 * 
 * @return Void
 */
function set_featured_image_on_save($post_id){
    $attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
    if(sizeof($attachments) > 0){
        set_post_thumbnail($post_id, $attachments[0]->ID);
    }else{
        // not loaded the we upload it as an attachment
        // required libraries for media_sideload_image
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        // load the image
        $img  = catch_that_image();
        if ("/images/default.jpg" != $img){
            $result = media_sideload_image($img, $post_id);
            $attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
            if(sizeof($attachments) > 0)
                set_post_thumbnail($post_id, $attachments[0]->ID);
        }else{
            //no images found
            return;
        }
    }
}



add_action( 'save_post', 'auto_set_post_image' );

/**
 * runs on post save and check's if we already have a post thumbnail, if not it gets one
 * 
 * @param  (int) $post_id 
 * @return Void
 */
function auto_set_post_image( $post_id ) {
    // verify if this is an auto save routine. 
      // If it is our form has not been submitted, so we dont want to do anything
      if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
          return;

    // Check permissions
    if ( 'page' == $_POST['post_type'] ){
        if ( !current_user_can( 'edit_page', $post_id ) )
        return;
    }else{
        if ( !current_user_can( 'edit_post', $post_id ) )
            return;
    }

    // OK, we're authenticated: we need to find and save the data

    //check if we have a post thumnail set already
    $attch = get_post_meta($post_id,"_thumbnail_id",true);
    if (empty($attch)){
        set_featured_image_on_save($post_id);
    }
}
share|improve this answer
    
I inserted the three functions inside my functions.php of my theme and when I publish/update a post, it gives me a 500 error :S I dont understand why. –  Gixty Mar 14 '12 at 16:22
    
maybe because post_id is unknown?? –  Gixty Mar 14 '12 at 16:58
add comment

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.