Getting static images for YouTube videos ready for your WordPress posts

This one’s a little complicated, but it’s a neat trick to getting static images for YouTube videos ready for your WordPress posts.

Lets say you want a site that uses lots of embedded YouTube videos. You want to show an index of these videos on your front page, or as an archive, but you don’t want to fetch an embed from YouTube for every video – you’d rather use something like featured images, but without having to do a screen grab, crop it, resize it, and upload.

Well, here’s a snippet that creates an automatic thumbnail from a YouTube URL when you save a post. To make this work you will need a piece of meta-data (the snippet uses ’_mytheme_embed_url’). When a post with this meta data item is saved, the snippet creates a new meta-data item called ’_mytheme_video_img_url’ with the URL of the thumbnail in.

You can use the thumbnail in your theme by doing something like:

  $preview_img = get_post_meta( get_the_ID(), ’_mytheme_video_img_url', true );
  if ($preview_img) {
    printf( '<img src="%s" />', $preview_img );
  }

Here’s the snippet:

// This action attempts to generate a YouTube thumbnail URL from the provided YouTube URL.
add_action( 'updated_post_meta', 'mytheme_generate_youtube_url', 10, 4);
add_action( 'added_post_meta', 'mytheme_generate_youtube_url', 10, 4);
function mytheme_generate_youtube_url( $meta_id, $object_id, $meta_key, $meta_value ) {
    if ($meta_key == '_mytheme_embed_url') {
        if (strlen($meta_value) > 7 ) { // Eliminates default 'http://'
            if (preg_match( '/youtube.com/', $meta_value )) {
                if (preg_match ('/\/embed\/(.*)/', $meta_value, $vid_matches )) {
                    $vid_tmp = $vid_matches[1];
                    $vid_tmp = explode('?', $vid_tmp);
                    $vid = $vid_tmp[0];
                } else {
                    $url_query = parse_url( $meta_value, PHP_URL_QUERY );
                    parse_str( $url_query, $params );
                    $vid = $params['v'];
                }
            } elseif (preg_match( '/youtu.be/', $meta_value )) {
                $vid = ltrim( parse_url( $meta_value, PHP_URL_PATH ), '/');
            }
            if ($vid) {
                $img_url = sprintf('http://i.ytimg.com/vi/%s/hqdefault.jpg', $vid);
                update_post_meta( $object_id, '_mytheme_video_img_url', $img_url );
            }
        }
    }
}

There’s a full write up of this on my own blog.

Credits:

This is mostly my own collation of things I found elsewhere so here are my sources – with thanks!

About

Ross loves using WordPress to help good causes, nicely structured code, and, at this time of year, a glass of ginger wine in front of a log fire.

Leave a Reply

Your email address will not be published. Required fields are marked *