Last active
July 31, 2020 07:52
-
-
Save petertwise/30ec9f6779c0e8cdf12e337c665d96c5 to your computer and use it in GitHub Desktop.
Get the best version of youtube cover image without using the API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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