Hack: Automatically Using YouTube Images as Thumbnails

If you have lots of posts that feature YouTube videos you may want to add a featured image for that post that is a frame of that video. But YouTube already creates and hosts thumbnails for these videos. So a quick and easy hack is to use these YouTube thumbnails as your post thumbnail so you have images for the posts that appear on the home page and category pages of your site.

<?php
/*
Plugin Name: WP Tips and Hacks YouTube Thumbnail As Featured Image
Plugin URI: 
Description: If there is a YouTube video embedded in the post, and there is no other thumbnail, then use a link to the YouTube video thumbnail as the featured image
Author: Gary Rosenzweig
Version: 1.0
Author URI: 
*/

add_filter('post_thumbnail_html', 'youtube_thumbnail');
function youtube_thumbnail($html) {
	if (has_post_thumbnail()) return $html; // has a real featured image
	
	// get youtube ID
	$content = get_post();
	$content = $content->post_content;
	if (preg_match('/youtu.be\/(.*?)"/', $content, $match) == 1) $youtubeid = $match[1];
	if ($youtubeid == null) return $html;
	
	// use this youtube link
	return "<img src=\"https://img.youtube.com/vi/".$youtubeid."/mqdefault.jpg\">";
}

Leave a Reply

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