我将尝试将远程服务器上的图片复制到我的WordPress网站中作为缩略图使用。但是在复制过程中,有些图片会变得损坏。
以下是我的代码:
$url = 'http://media.cultserv.ru/i/1000x1000/'.$event->subevents[0]->image;
$timeout_seconds = 100;
$temp_file = download_url( $url, $timeout_seconds );
if(!is_wp_error( $temp_file )) {
$file = array(
'name' => basename($url),
'type' => wp_check_filetype(basename($url), null),
'tmp_name' => $temp_file,
'error' => 0,
'size' => filesize($temp_file),
);
$overrides = array(
'test_form' => false,
'test_size' => true,
'test_upload' => true,
);
$results = wp_handle_sideload( $file, $overrides );
if(empty($results['error'])) {
$filename = $results['file'];
$local_url = $results['url'];
$type = $results['type'];
$attachment = array(
'post_mime_type' => $results['type'],
'post_title' => preg_replace('/.[^.]+$/', '', basename( $results['file'] ) ),
'post_content' => '',
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_parent' => $pID,
);
$attachment_id = wp_insert_attachment( $attachment, $filename );
if($attachment_id) {
set_post_thumbnail( $pID, $attachment_id );
}
}
}
这是一张截图,左边是原始图片,右边是我服务器上的复制品:
set_post_thumbnail
之前使用$attachData = wp_generate_attachment_metadata($attachment_id, $filename);
和wp_update_attachment_metadata($attach_id, $attachData);
,看看结果是否会改善。同时确保在脚本的某个地方使用require_once( ABSPATH . 'wp-admin/includes/image.php' );
。 - Will B.