using media_sideload_image with a file from theme directory
I'm building a Wordpress site in which an admin can upload a video file from post metabox.
After that post is saved and the video file is attached to the post, I used ffmpeg to get the screenshot at the first second of video, then save this screenshot as a JPG file in 'tmp' directory in theme directory.
Finally, I want to programmatically make this screenshot as post featured image. I use media_sideload_image function, which generally be used to get image from another server and set that image as post featured image and I think this function could be used in this case also.
In my case, the video screenshot was successfully saved to 'tmp' directory in my theme dir, but the media_sideload_image part did not return anything for further process. Here's my function:
function create_video_featured_image($post_id, $image_uri) {
// $image_uri = 'http://localhost/demo-site/wp-content/themes/mytheme/tmp/video_thumb_952.jpg';
$media = media_sideload_image($image_uri, $post_id);
if(!empty($media) !is_wp_error($media)){
$args = array(
'post_type' = 'attachment',
'posts_per_page' = -1,
'post_status' = 'any',
'post_parent' = $post_id
);
// reference new image to set as featured
$attachments = get_posts($args);
if(isset($attachments) is_array($attachments)){
foreach($attachments as $attachment){
// grab source of full size images (so no 300x150 nonsense in path)
$image = wp_get_attachment_image_src($attachment-ID, 'full');
// determine if in the $media image we created, the string of the URL exists
if(strpos($media, $image[0]) !== false){
// if so, we found our image. set it as thumbnail
set_post_thumbnail($post_id, $attachment-ID);
// only want one image
break;
}
}
}
}
}
Am I missing anything or is there another way to work around in this case ?
Thank you very much !