Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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