View Single Post
Old December 10th, 2012, 08:58 PM
jerseyal jerseyal is offline
Join Date: Sep 2012
Posts: 56


Your code does just what you said it does, but unfortunately, it slows down my site to where it take 30 seconds for pages to load. Have you noticed any performance issues after inserting this code? Also, the featured images are very large, and if I click on it in the WP post page, and look in media gallery, there seems to be over 20 of the same image. Don't know if any of this is related...

What do you think?


Originally Posted by Reson8 View Post
Hi Eric,

Here is what I used to fix this up in my site if it's useful for other users. Paste the code below into the functions.php file. The uploads folder needs to be writable (permissions 777) and the hosting server Must Support file_get_content/fopen/fputs:

function postmeta_img_update() {
global $post;
// If Custom Post Meta Field for a Image/Thumnail Exists
if( get_post_meta($post->ID, "store_image", true) ):

// Get Image Location and File Extention
$img = get_post_meta($post->ID, "store_image", true);
$ext = substr(strrchr($img,'.'),1);

// WordPress Upload Directory to Copy to (must be CHMOD to 777)
$uploads = wp_upload_dir();
$copydir = $uploads['path']."/";

// Code to Copy Image to WordPress Upload Directory (Server Must Support file_get_content/fopen/fputs)
$data = file_get_contents($img);
$filetitle = strtolower(str_replace(array(' ', '-', '.', '(', ')', '!', '@', '#', '$', '%', '^', '&', '*', '_', '=', '+'), "-", get_the_title()));
$file = fopen($copydir . "$filetitle-$post->ID.$ext", "w+");
fputs($file, $data);

// Insert Image to WordPress Media Libraby
$filepath = $uploads['path']."/$filetitle-$post->ID.$ext";

$wp_filetype = wp_check_filetype(basename($filepath), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => get_the_title(),
'post_content' => 'Image for '.get_the_title(),
'post_status' => 'inherit'

wp_insert_attachment($attachment, $filepath, $post->ID);

// Get Attachment ID for Post
global $wpdb; $attachment_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_parent = '$post->ID' AND post_status = 'inherit' AND post_type='attachment' ORDER BY post_date DESC LIMIT 1");

// Attached Image as Featured Thumbnail in Post
update_post_meta($post->ID, "_thumbnail_id", $attachment_id);

// Removes Custom Meta Field Image URL. This stop this function running again for the updated post.
delete_post_meta($post->ID, "image");