0

I have a save post hook that looks like this, it should download youtube thumbnail to wp-includes/uploads base on video id provided. But it doesnt save anything.

 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);
}
}

});
  • Did you check your directory permissions? – Pim Sep 12 '18 at 10:49
2

There is special wp_upload_bits() function to upload the content to the 'uploads' directory. Also, there is no such directory as /wp-includes/upload/.

The code was not tested!

<?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>';

}
1

I'd advice you to use WordPress' API functionality for this, like media_sideload_image(), media_handle_sideload() or media_handle_upload(). Just to name some of the obvious ones, in the end it is depending on what your goal is. You'll find use cases at the WordPress Developer Reference or on here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.