function set_youtube_as_featured_image($post_id) {
if( has_post_thumbnail($post_id) ) return;
$url = get_post_meta($post_id, 'ci_cpt_video_link', true);
if ( $url && filter_var($url, FILTER_VALIDATE_URL) ) {
// getting thumb url from video url
parse_str( parse_url( $url, PHP_URL_QUERY ), $youtube_vars );
$youtube_id = $youtube_vars['v'];
$youtube_thumb_url="http://img.youtube.com/vi/" . $youtube_id . '/0.jpg';
// download and save thumb
$get = wp_remote_get( $youtube_thumb_url );
$mime_type = wp_remote_retrieve_header( $get, 'content-type' );
if ( ! substr_count($mime_type, 'image') ) return false;
$name="youtube-thumb-post-" . $post_id . '.jpg';
$bits = wp_upload_bits( $name, '', wp_remote_retrieve_body( $get ) );
if ( $bits['error'] ) return false;
// save attachment post, and setting as post thumbnails
$thumb_data = array(
'post_title'=> 'Youtube Preview', 'post_mime_type' => $mime_type
);
$thumbnail_id = wp_insert_attachment( $thumb_data, $bits['file'], $post_id );
if ( $thumbnail_id ) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$metadata = wp_generate_attachment_metadata( $thumbnail_id, $bits['file'] );
wp_update_attachment_metadata( $thumbnail_id, $metadata );
set_post_thumbnail( $post, $thumbnail_id );
}
}
}
add_action('save_post', 'set_youtube_as_featured_image');