extract post image to be featured images

I been working with featured images more lately and I been adding them to my posts as I go. However I have a bunch of older posts that do not have the featured image set and I want to use it for such things as wptouch etc.

So I have like 300 posts and to be honest I dont want to go into 300 posts and set the images manually.

IS there anyway either by plugin or code that you can code it where the featured images area will grab the first image in each post?

2 Answers
2

if the image is inserted (attached) into the post and not a external link:

function get_my_thumbnail($post_id, $size, $attr=""){

  // check of featured image first
  $t = get_post_thumbnail_id($post_id);

  // no featured image set, check post attachments
  if(empty($t)){
    $attachments = get_children(array(
      'post_parent'    => $post_id,
      'post_status'    => 'inherit',
      'post_type'      => 'attachment',
      'post_mime_type' => 'image',
      'order'          => 'ASC',
      'orderby'        => 'menu_order ID',
    ));
    $attachment = array_shift($attachments); // we only need one
    $t = $attachment ? $attachment->ID : false;
  } 

  // no attachments either...
  if(empty($t)) return 'no image...';

  // we have either attachment / featured image, so output the post thumbnail
  do_action('begin_fetch_post_thumbnail_html', $post_id, $t, $size); // compat
  $html = wp_get_attachment_image($t, $size, false, $attr);
  do_action('end_fetch_post_thumbnail_html', $post_id, $t, $size);

  return $html;
}

You may want to also regenerate all attachment sizes (auto-create $size-d images from your older ones), so you don’t get browser-resized huge images…

Leave a Comment