本文章测试于 WordPress 4.4.2
这儿需要用的两个插件
- 阿里云附件存储 [http://yii.im/posts/aliyun-oss-support-plugin-for-wordpress]
- Auto Post Thumbnail [https://wordpress.org/plugins/auto-post-thumbnail/]
接下来 要对 auto post thumbnail 里的函数 apt_generate_post_thumb 稍作修改,将文件下载保存在本地替换成使用 wp_handle_sideload 上传到OSS
/**
* Function to fetch the image from URL and generate the required thumbnails
*/
function apt_generate_post_thumb($matches, $key, $post_content, $post_id)
{
// Make sure to assign correct title to the image. Extract it from img tag
$imageTitle = '';
preg_match_all('/<\s*img [^\>]*title\s*=\s*[\""\']?([^\""\'>]*)/i', $post_content, $matchesTitle);
if (count($matchesTitle) && isset($matchesTitle[1])) {
$imageTitle = $matchesTitle[1][$key];
}
// Get the URL now for further processing
$imageUrl = $matches[1][$key];
// Get the file name
$filename = substr($imageUrl, (strrpos($imageUrl, '/'))+1);
if (!(($uploads = wp_upload_dir(current_time('mysql')) ) && false === $uploads['error'])) {
return null;
}
// Generate unique file name
$filename = wp_unique_filename( $uploads['path'], $filename );
// gives us access to the download_url() and wp_handle_sideload() functions
if ( ! function_exists( 'download_url' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$timeout_seconds = 5;
// download file to temp dir
$temp_file = download_url( $imageUrl, $timeout_seconds );
if (!is_wp_error( $temp_file )) {
// array based on $_FILE as seen in PHP file uploads
$file = array(
'name' => basename($imageUrl), // ex: wp-header-logo.png
'type' => 'image/png',
'tmp_name' => $temp_file,
'error' => 0,
'size' => filesize($temp_file),
);
$overrides = array(
// tells WordPress to not look for the POST form
// fields that would normally be present, default is true,
// we downloaded the file from a remote server, so there
// will be no form fields
'test_form' => false,
// setting this to false lets WordPress allow empty files, not recommended
'test_size' => true,
// A properly uploaded file will pass this test.
// There should be no reason to override this one.
'test_upload' => true,
);
// move the temporary file into the uploads directory
$results = wp_handle_sideload( $file, $overrides );
if (!empty($results['error'])) {
// insert any error handling here
return null;
} else {
$filename = $results['file']; // full path to the file
$local_url = $results['url']; // URL to the file in the uploads dir
$type = $results['type']; // MIME type of the file
$attachment = array(
'post_mime_type' => $type,
'guid' => $local_url,
'post_parent' => null,
'post_title' => $imageTitle,
'post_content' => '',
);
$thumb_id = wp_insert_attachment($attachment, $filename, $post_id);
if ( !is_wp_error($thumb_id) ) {
require_once(ABSPATH . '/wp-admin/includes/image.php');
// Added fix by misthero as suggested
wp_update_attachment_metadata( $thumb_id, wp_generate_attachment_metadata( $thumb_id, $filename ) );
update_attached_file( $thumb_id, $filename );
return $thumb_id;
}
}
}
return null;
}