Skip to content

Instantly share code, notes, and snippets.

@tylerreed
Last active March 11, 2022 02:19
Show Gist options
  • Save tylerreed/5869822 to your computer and use it in GitHub Desktop.
Save tylerreed/5869822 to your computer and use it in GitHub Desktop.
A snippet of code to create static featured images for a WordPress post using a YouTube or Vimeo video URL. I have used this code for several projects where video posts or embedded videos needed to be static images in order to be more mobile friendly as well as for improve page load times when used as a featured image for the post.
<?php
/*
A snippet of code to create static featured images for a WordPress post using
a YouTube or Vimeo video URL. I have used this code for several projects where
video posts or embedded videos needed to be static images in order to be more
mobile friendly as well as for improved page load times when used as a featured
image for the post.
I have added comments where it might be neccessary to modify the code or where
there is room for improvement. There are two primary functions to be used
depending on your objective.
1. "replace_videos" can be used to replace all embedded videos with a static
thumbnail of the video.
2. "set_featured_image" can be used to set the featured of a specific post with
the thumbnail of a video.
*/
// -----------------------------------------------
// Example Function Call for replace_videos
// -----------------------------------------------
// Could use any method for fetching a post's data
// or even loop through a bunch of posts to do this
// in bulk.
$post_content = 'Insert Post Content with Embedded Video(s) Here.';
replace_videos( $post_content );
// -----------------------------------------------
// Example Function Call for set_featured_image
// -----------------------------------------------
// Could use any method for fetching a post's data
// or even loop through a bunch of posts to do this
// in bulk.
$post_id = '1';
// Video URL can be retrieved with in the post's
// content or from meta data associated with the
// post. Some WordPress themes have custom post
// data with a meta key for video posts.
$video_url = 'https://www.youtube.com/watch?v=oHg5SJYRHA0';
set_featured_image( $post_id, $video_url );
// -----------------------------------------------
// The Functions
// -----------------------------------------------
function replace_videos( $post_content ) {
// Check the post's content to see if there are
// any embedded videos from YouTube or Vimeo.
if ( preg_match_all( '#<(iframe|object).+?http://(www.youtube.com\/|vimeo.com\/|player.vimeo.com\/)(embed\/|moogaloop.swf\?clip_id=|v\/|video\/)([A-Za-z0-9\-_]+)(.*?)</(iframe|object)>#s', $post_content, $matches, PREG_SET_ORDER ) ) {
// Loop through each match to replace the embedded
// video with a thumbnail.
foreach ( $matches as $match ) {
$service_tag = $match[1];
$service_url = $match[2];
$service_embed = str_replace('?', '\?', $match[3] );
$service_id = $match[4];
// Now to fetch the video thumbnail depending
// on what service the video is hosted on.
if ( strpos( $video_url, 'youtube' ) > 0 ) {
$thumbnail = tr_youtube_thumbnail( $video_url );
} else if ( strpos( $video_url, 'vimeo' ) > 0 ) {
$thumbnail = tr_vimeo_thumbnail( $video_url );
}
// Replace the embed code with the image code.
// A library like TimThumb could be used to
// resize thumbnails accordingly.
if ( $service_url == 'www.youtube.com/' ) {
$service_img = '<img src="'. $thumbnail .'" /><br /><a href="http://m.youtube.com/watch?v='. $service_id .'">Watch on YouTube</a>';
} else if ( $service_url == 'vimeo.com/' || $service_url == 'player.vimeo.com/' ) {
$service_img = '<img src="'. $thumbnail .'" /><br /><a href="http://vimeo.com/'. $service_id .'">Watch on Vimeo</a>';
}
$post_content = preg_replace( '#<'. $service_tag .'.*?http://'. $service_url .''. $service_embed .''. $service_id .'(.*?)</'. $service_tag .'>#s', $service_img, $post_content );
}
}
return $post_content;
}
function set_featured_image() {
// Fetch the video thumbnail depending
// on what service the video is hosted on.
if ( strpos( $video_url, 'youtube' ) > 0 ) {
$thumbnail = tr_youtube_thumbnail( $video_url );
} else if ( strpos( $video_url, 'vimeo' ) > 0 ) {
$thumbnail = tr_vimeo_thumbnail( $video_url );
}
// If we have a thumbnail, let's set the image as featured.
if ( isset( $thumbnail ) ) {
$attachment_file = file_get_contents( $thumbnail );
$new_file_name = str_replace( ' ', '_', basename( $thumbnail ) );
$new_file_name = str_replace( '+', '_', $new_file_name );
// Determine the WordPress upload directory.
$wp_upload_dir = wp_upload_dir();
if ( file_put_contents( $wp_upload_dir['path'] . '/'. $new_file_name, $attachment_file ) ) {
$file_type = wp_check_filetype( $new_file_name );
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/'. _wp_relative_upload_path( $new_file_name ),
'post_mime_type' => $file_type['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $new_file_name ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the video thumbnail as an attachment to the post.
$attach_id = wp_insert_attachment( $attachment, $wp_upload_dir['path'] . '/'. $new_file_name, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $new_file_name );
// Update post meta data and set as a featured image.
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta( $post_id, '_thumbnail_id', $attach_id );
}
}
}
// Vimeo returns quite a bit of data, so one
// could use modify this function to fetch
// different thumbnail sizes, etc.
// See: https://developer.vimeo.com/apis/simple
// See: http://vimeo.com/api/v2/video/68420097.json
function fetch_vimeo_thumbnail( $video_url ) {
sscanf( parse_url( $video_url, PHP_URL_PATH ), '/%d', $video_id );
$vimeo_url = 'http://vimeo.com/api/v2/video/'. $video_id .'.json';
$vimeo_json = file_get_contents( $vimeo_url, 0, null, null );
$vimeo_data = json_decode( $vimeo_json, true );
$thumb_url = $vimeo_data[0]['thumbnail_large'];
return $thumb_url;
}
// Function could be modified to fetch different
// thumbnail sizes.
// See: https://developers.google.com/youtube/2.0/developers_guide_protocol
function fetch_youtube_thumbnail( $video_url ) {
$video_data = array();
parse_str( parse_url( $video_url, PHP_URL_QUERY ), $video_data );
$video_id = $video_data['v'];
$thumb_url = 'http://img.youtube.com/vi/'. $video_id .'/0.jpg';
return $thumb_url;
}
?>
@shikkaba
Copy link

Was the function tr_youtube_thumbnail supposed to be the fetch_youtube_thumbnail at the bottom?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment