Nov

13

WordPress Custom Field Image to Featured Image

Posted by CodeMunkyX

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:


	// First lets get the custom field , we are assuming its called "thumb"
	$thumb = get_post_meta($post->ID, 'thumb', true);

	// Check if a post thumbnail is already set, if so don't do anything.
	if( has_post_thumbnail( $post->ID ) ) {

	} else {

		if ( ! empty($thumb) ) {

			// Download file to temp location
			$tmp = download_url( $thumb );

			// Set variables for storage
			// fix file filename for query strings
			preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $thumb, $matches);
			$file_array['name'] = basename($matches[0]);
			$file_array['tmp_name'] = $tmp;

			// If error storing temporarily, unlink
			if ( is_wp_error( $tmp ) ) {
				@unlink($file_array['tmp_name']);
				$file_array['tmp_name'] = '';
			}

			// do the validation and storage stuff
			$id = media_handle_sideload( $file_array, $post->ID, NULL );
			// If error storing permanently, unlink
			if ( is_wp_error($id) ) {
				@unlink($file_array['tmp_name']);
				return $id;
			}

			// Set the featured image
			set_post_thumbnail( $post->ID, $id );

		}

	}

Tags:

Socialize

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

featured wordpress themes