Skip to content

Instantly share code, notes, and snippets.

@petertwise
Last active July 31, 2020 07:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save petertwise/30ec9f6779c0e8cdf12e337c665d96c5 to your computer and use it in GitHub Desktop.
Save petertwise/30ec9f6779c0e8cdf12e337c665d96c5 to your computer and use it in GitHub Desktop.
Get the best version of youtube cover image without using the API
<?php
function url_exists( $url ) {
$headers = get_headers($url);
return stripos( $headers[0], "200 OK" ) ? true : false;
}
function get_youtube_id( $url ) {
$youtubeid = explode('v=', $url);
$youtubeid = explode('&', $youtubeid[1]);
$youtubeid = $youtubeid[0];
return $youtubeid;
}
function get_youtube_thumb( $id ) {
if ( url_exists( 'https://i.ytimg.com/vi_webp/' .$id . '/maxresdefault.webp' ) ) {
$image = 'https://i.ytimg.com/vi_webp/' .$id . '/maxresdefault.webp';
}
elseif ( url_exists( 'https://i.ytimg.com/vi_webp/' .$id . '/mqdefault.webp' ) ) {
$image = 'https://i.ytimg.com/vi_webp/' .$id . '/mqdefault.webp';
}
elseif ( url_exists( 'https://i.ytimg.com/vi/' .$id . '/maxresdefault.jpg' ) ) {
$image = 'https://i.ytimg.com/vi/' .$id . '/maxresdefault.jpg';
}
elseif ( url_exists( 'https://i.ytimg.com/vi/' .$id . '/mqdefault.jpg' ) ) {
$image = 'https://i.ytimg.com/vi/' .$id . '/mqdefault.jpg';
}
else {
$image = false;
}
return $image;
}
// Example:
$youtube_url = 'https://www.youtube.com/watch?v=ferZnZ0_rSM';
$id = get_youtube_id( $youtube_url );
$thumb = get_youtube_thumb( $id );
echo '<img src="' . $thumb . '" alt="">';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment