Convert Custom Field image to become Featured Image in WordPress?

I run a css gallery and I need to convert all the images in the gallery from a Custom Field to become the Featured Image.
Does anyone have any advice how I could do this?

Related posts

Leave a Reply

1 comment

  1. OK, firstly, if you want to avoid TimThumb entirely and your images aren’t currently the right size, you’ll need to find a plugin that can batch resize your media library.

    Once you’ve done that, we can attempt to automate the process of finding the attachment for each featured image (that is, the post entry in the wp_posts table), and setting the post thumbnail.

    $uploads = wp_upload_dir();
    
    // Get all attachment IDs and filenames
    $results = $wpdb->get_results("SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file'");
    
    // Create an 'index' of attachment IDs and their filenames
    $attachments = array();
    foreach ($results as $row)
        $attachments[ intval($row->post_id) ] = $row->meta_value;
    
    // Get all featured images
    $images = $wpdb->get_results("SELECT post_id, meta_value AS 'url' FROM $wpdb->postmeta WHERE meta_key = 'Featured Image'");
    
    // Loop over each image and try and find attachment post
    foreach ($images as $image) {
        if (preg_match('#^https?://#', $image->url))
            $image->url = str_replace($uploads['baseurl'], '', $image->url); // get relative URL if absolute
    
        $filename = ltrim($image->url, '/');
    
        if ($attachment_ID = array_search($filename, $attachments)) {
            // found attachment, set post thumbnail and delete featured image
            update_post_meta($image->post_id, '_thumbnail_id', $attachment_ID);
            delete_post_meta($image->post_ID, 'Featured Image');
        }
    }
    

    Disclaimer

    There is no guarantee that the code above will work, it’s purely based on the information I have gauged from your comments so far – it’s more of a suggestion than a one-stop solution.