WordPress Custom Field Image to Featured Image

7:03:00 PM | ,

Do you have a theme that uses custom fields to hold image URLS and wish you could automatically set these as the featured post image, to be more compatable with other themes if you ever decided to change.
Well today is your lucky day, I ran across the need to do this on one of my recent free themes. Below is the code:
1// First lets get the custom field , we are assuming its called "thumb"
2$thumb = get_post_meta($post->ID, 'thumb', true);
3 
4// Check if a post thumbnail is already set, if so don't do anything.
5if( has_post_thumbnail( $post->ID ) ) {
6 
7else {
8 
9    if ( ! empty($thumb) ) {
10 
11        // Download file to temp location
12        $tmp = download_url( $thumb );
13 
14        // Set variables for storage
15        // fix file filename for query strings
16        preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/'$thumb$matches);
17        $file_array['name'] = basename($matches[0]);
18        $file_array['tmp_name'] = $tmp;
19 
20        // If error storing temporarily, unlink
21        if ( is_wp_error( $tmp ) ) {
22            @unlink($file_array['tmp_name']);
23            $file_array['tmp_name'] = '';
24        }
25 
26        // do the validation and storage stuff
27        $id = media_handle_sideload( $file_array$post->ID, NULL );
28        // If error storing permanently, unlink
29        if ( is_wp_error($id) ) {
30            @unlink($file_array['tmp_name']);
31            return $id;
32        }
33 
34        // Set the featured image
35        set_post_thumbnail( $post->ID, $id );
36 
37    }
38 
39}