Skip to content

Instantly share code, notes, and snippets.

@lmoncany
Created April 3, 2023 13:09
Show Gist options
  • Save lmoncany/4fec29d69da4b105dc07062957591df2 to your computer and use it in GitHub Desktop.
Save lmoncany/4fec29d69da4b105dc07062957591df2 to your computer and use it in GitHub Desktop.
Save youtube thumbnail to featured image in wp
/* Shortcode to display youtube thumbnail on your wordpress blog.
Usage:*/
/**
* Download image, attach it to the current post, and assign it as featured image
* upon publishing the post.
*
* The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
* refer to the new post status and post type, respectively.
*
* Please note: When this action is hooked using a particular post status (like
* 'publish', as `publish_{$post->post_type}`), it will fire both when a post is
* first transitioned to that status from something else, as well as upon
* subsequent post updates (old and new status are both the same).
*
* @param int $post_id Post ID.
* @param WP_Post $post Post object.
*/
add_action( 'save_post', 'wpse_default_featured_image', 10, 2 );
function wpse_default_featured_image( $post_id, $post ) {
// Bail if there is already a post thumbnail set.
$current_post_thumbnail = get_post_thumbnail_id( $post_id );
if ( '' !== $current_post_thumbnail && $post->post_type != 'video') {
return;
}
// Get Youtube URL
// $yturl = get_post_meta('url-video' , $post_id);
$yturl = get_post_meta($post->ID, 'url-video', true);;
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $yturl, $matches);
$video_id = $matches[1];
// Get Thumbnail
$file_headers = get_headers( 'https://img.youtube.com/vi/' . $video_id . '/maxresdefault.jpg' );
$is_404 = $file_headers[0] == 'HTTP/1.0 404 Not Found' || false !== strpos( $file_headers[0], '404 Not Found' );
$video_thumbnail_url = 'https://img.youtube.com/vi/' . $video_id . '/maxresdefault.jpg';
$url = $video_thumbnail_url;
$title = "The default featured image.";
$image = media_sideload_image( $url, $post_id, $title, 'id' );
set_post_thumbnail( $post_id, $image );
error_log( 'MY STUFF: ' . print_r( $yturl, true ) );
error_log( 'MY STUFF: ' . print_r( $id, true ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment