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:
2 | $thumb = get_post_meta( $post ->ID, 'thumb' , true); |
5 | if ( has_post_thumbnail( $post ->ID ) ) { |
9 | if ( ! empty ( $thumb ) ) { |
12 | $tmp = download_url( $thumb ); |
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 ; |
21 | if ( is_wp_error( $tmp ) ) { |
22 | @unlink( $file_array [ 'tmp_name' ]); |
23 | $file_array [ 'tmp_name' ] = '' ; |
27 | $id = media_handle_sideload( $file_array , $post ->ID, NULL ); |
29 | if ( is_wp_error( $id ) ) { |
30 | @unlink( $file_array [ 'tmp_name' ]); |
35 | set_post_thumbnail( $post ->ID, $id ); |