# Set post-thumbnail (with php)?

A site I have inherited uses custom fields to set a path for thumbnails. Ideally I'd like to switch this over to use the built in post-thumbnail. Is there a way to procedurally set the post-thumbnail?

Thanks

-
–  Michal Mau Aug 17 '11 at 13:48

The issue is going to be the difference in the data required for setting the post thumbnail (an attachment ID) and what's probably in the custom field: a URL.

The way I'm going to suggest is very sloppy: adds more attachments to WordPress. A better way might be to write a custom SQL query where you grab the attachment ID from the custom field URL. This works, it just might not be the best way.

First, get all the posts:

// get an array of all the posts
$posts = get_posts( array( 'numberposts' => -1, 'post_type' => 'post' ) ); // bail if our get_posts() call failed if( empty($posts ) ) return;


Then we'll loop through them, grabbing the original Image URL, then inserting it as a new attachment. Finally, we'll update the postmeta table to reflect our new thumbnail ID and get rid of the old post thumbnail custom field.

foreach( $posts as$p )
{
// change your old thumbnail key!
$image_url = get_post_meta($p->ID, 'your_old_thumbnail_key', true );

// no thumbnail? on to the next
if( empty( $image_url ) ) continue; // find our mime type for later$filetype = wp_check_filetype( $image_url ); // Set up an array of args for our new attachment$args = array(
'post_mime_type' => $filetype['type'], 'post_title' => esc_attr($p->post_title ), // you may want something different here
'post_content'   => '',
'post_status'    => 'inherit'
);

// Insert the attachment!
$thumb_id = wp_insert_attachment($args, $image_url,$p->ID );

// gotta set up some meta data (height, width, etc)
// our functions are int his file, so we have to include it
$metadata = wp_generate_attachment_metadata($thumb_id, $image_url ); wp_update_attachment_metadata($thumb_id, $metadata ); // Finally! set our post thumbnail update_post_meta($p->ID, '_thumbnail_id', $thumb_id ); // Uncomment the next line to delete the old custom field //delete_post_meta($p->ID, 'your_old_thumbnail_key', \$image_url );