问题将是设置帖子缩略图(附件ID)所需的数据与自定义字段中可能存在的内容(URL)之间的差异。
我建议的方式非常草率:在WordPress中添加更多附件。更好的方法可能是编写自定义SQL查询,从自定义字段URL获取附件ID。这很有效,但可能不是最好的方法。
首先,获取所有帖子:
// get an array of all the posts
$posts = get_posts(
array(
\'numberposts\' => -1,
\'post_type\' => \'post\'
)
);
// bail if our get_posts() call failed
if( empty( $posts ) ) return;
然后我们将遍历它们,获取原始图像URL,然后将其作为新附件插入。最后,我们将更新Posteta表以反映新的缩略图ID,并去掉旧的post缩略图自定义字段。
foreach( $posts as $p )
{
// change your old thumbnail key!
$image_url = get_post_meta( $p->ID, \'your_old_thumbnail_key\', true );
// no thumbnail? on to the next
if( empty( $image_url ) ) continue;
// find our mime type for later
$filetype = wp_check_filetype( $image_url );
// Set up an array of args for our new attachment
$args = array(
\'post_mime_type\' => $filetype[\'type\'],
\'post_title\' => esc_attr( $p->post_title ), // you may want something different here
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
// Insert the attachment!
$thumb_id = wp_insert_attachment( $args, $image_url, $p->ID );
// gotta set up some meta data (height, width, etc)
// our functions are int his file, so we have to include it
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$metadata = wp_generate_attachment_metadata( $thumb_id, $image_url );
wp_update_attachment_metadata( $thumb_id, $metadata );
// Finally! set our post thumbnail
update_post_meta( $p->ID, \'_thumbnail_id\', $thumb_id );
// Uncomment the next line to delete the old custom field
//delete_post_meta( $p->ID, \'your_old_thumbnail_key\', $image_url );
}
就是这样!
这里是一个插件:http://pastie.org/2386814