Automatic Featured Images for YouTube Posts

A few people have asked how I get the WordPress featured image for my YouTube posts. It’s actually quite simple – YouTube provides a thumbnail for each video you publish (in the form of http://img.youtube.com/vi/{video_id}/0.jpg) that is free for the taking.

Here is a little script that detects a YouTube embed and automatically downloads, imports, and assigns your YouTube thumbnail as the posts’ featured image. Remove lines 3 and 4 if you’re not using post formats.

function rdc_youtube_video_post( $post_id ) {
// No need to continue if it's not a video post
if ( 'video' != get_post_format( $post_id ) )
return false;

// No need to continue if we already have a post thumbnail
if ( has_post_thumbnail( $post_id ) )
return false;

// Get the post content
$the_post = get_post( $post_id );
$the_content = $the_post->post_content;

// No need to continue if we haven't inserted a youtube embed
if ( false === strpos( $the_content, 'www.youtube.com/embed/' ) )
return false;

// Extract the youtube ID
$matches = array();
preg_match_all( '/www.youtube.com/embed/(.*?)(?|")/i', $the_content, $matches );
$yt_id = $matches[1][0];

// Bail if we don't have a valid Youtube ID
if ( ! $yt_id || empty( $yt_id ) )
return false;

// Get the URL of the YouTube thumbnail
$yt_image_url = 'http://img.youtube.com/vi/' . $yt_id . '/0.jpg';

// Set up for importing and grab the remote image
$upload_dir = wp_upload_dir();
$image_contents = file_get_contents( $yt_image_url );
$filename = sanitize_file_name( basename( $yt_id . '.jpg' ) );

// Create the upload directory if we must
if ( wp_mkdir_p( $upload_dir['path'] ) )
$file = trailingslashit( $upload_dir['path'] ) . $filename;
else
$file = trailingslashit( $upload_dir['basedir'] ) . $filename;

// Store the image file on the server
file_put_contents( $file, $image_contents );

// Check the mime type of the file
$mimetype = wp_check_filetype( $filename, null );

// Consolidate some details about the attachment
$attachment = array(
'post_mime_type' => $mimetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit',
);

// Insert the attachment into WordPress
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );

// We need some additional functions
require_once( ABSPATH . 'wp-admin/includes/image.php' );

// Generate and save the attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );

// Finally, set the post thumbnail to use our youtube image
set_post_thumbnail( $post_id, $attach_id );
}
add_action( 'save_post', 'rdc_youtube_video_post' );

4 thoughts on “Automatic Featured Images for YouTube Posts”

Leave a Reply