要为帖子设置缩略图,应将文件上载到服务器。使用以下功能从URL上载文件:
function upload_file($image_url, $post_id)
{
$image = $image_url;
$get = wp_remote_get($image);
$type = wp_remote_retrieve_header($get, \'content-type\');
if (!$type) {
return false;
}
$mirror = wp_upload_bits(basename($image), \'\', wp_remote_retrieve_body($get));
$attachment = array(
\'post_title\' => basename($image),
\'post_mime_type\' => $type
);
$attach_id = wp_insert_attachment($attachment, $mirror[\'file\'], $post_id);
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$attach_data = wp_generate_attachment_metadata($attach_id, $mirror[\'file\']);
wp_update_attachment_metadata($attach_id, $attach_data);
return $attach_id;
}
然后运行函数:
$url = \'http://yoursite.com/photo.jpg\';
$post_id = 56;
upload_file($url, $post_id);