我有一个保存帖子的钩子,看起来像这样,它应该根据提供的视频id将youtube缩略图下载到wp包含/上传。但这并不能挽救任何东西。
add_filter( \'save_post\', function () {
$video_id = \'VSB4wGIdDwo\';
$path_to_save_thumbnails = \'/wp-includes/upload/\';
$ch = curl_init();
$thubnail_types = array(\'0\', \'1\', \'2\', \'3\',\'default\',
\'sddefault\', \'mqdefault\',
\'hqdefault\', \'maxresdefault\');
foreach($thubnail_types as $type)
{
$youtube_thumb_url =
\'http://img.youtube.com/vi/\'.$video_id.\'/\'.$type.\'.jpg\';
echo "Downloading thumbnail [$type]." . PHP_EOL;
curl_setopt($ch, CURLOPT_URL, $youtube_thumb_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$image = curl_exec($ch);
$info = curl_getinfo($ch);
if($info[\'http_code\'] == 200) {
file_put_contents($path_to_save_thumbnails.$type.\'.jpg\', $image);
}
}
});
SO网友:Max Yudin
有特别的wp_upload_bits()
函数将内容上载到“uploads”目录。此外,没有这样的目录/wp-includes/upload/
.
代码未经测试!
<?php
$video_id = \'xxxxxxxxxxxxx\';
$thumbnail_types = array(
\'0\',
\'1\',
\'2\',
\'3\',
\'default\',
\'sddefault\',
\'mqdefault\',
\'hqdefault\',
\'maxresdefault\',
);
foreach( $thumbnail_types as $type ) {
$file_name = $type . \'.jpg\';
$youtube_thumb_url = \'http://img.youtube.com/vi/\' . $video_id . \'/\' . $file_name;
$thumbnail_file = file_get_contents( $youtube_thumb_url );
// Where the magic happens
$uploaded_file = wp_upload_bits( $file_name, null, $thumbnail_file );
// check the result
echo \'<pre>\';
print_r( $uploaded_file ) ; // path, URL, file type and error message
echo \'</pre>\';
}