Skip to content

Instantly share code, notes, and snippets.

@epschmidt
Created September 8, 2017 13:32
Show Gist options
  • Save epschmidt/8ccddc16267f9e2a81bc80df8792035b to your computer and use it in GitHub Desktop.
Save epschmidt/8ccddc16267f9e2a81bc80df8792035b to your computer and use it in GitHub Desktop.
Return video embed info from YouTube and Vimeo by URL
function get_video_data($url) {
$id = '';
$result = '';
$video = array();
$split_url = parse_url( $url );
if ( isset( $split_url['host'] ) ) {
$video['host'] = $split_url['host'];
// Youtube Thumbnail
if (preg_match("/^(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$/", $url, $matches))
{
$id = $matches[1];
$response = wp_remote_get('http://www.youtube.com/oembed/?url=' . $url . '&format=json');
$hash = @json_decode($response['body'], true);
$thumbnail_url = 'https://img.youtube.com/vi/' . $id . '/maxresdefault.jpg';
$thumbnail_small_url = 'https://img.youtube.com/vi/' . $id . '/0.jpg';
if( is_array($hash) )
{
$data = array(
'id' => $id,
'hash' => 'px-' . rand(1, 100) . '-' . $id,
'thumbnail' => $thumbnail_url,
'thumbnail_small' => $thumbnail_small_url,
'embed_url' => 'http://www.youtube.com/embed/' . esc_attr($id) . '?autoplay=1',
'caption' => $hash['title']
);
}
} elseif ( $video['host'] == 'www.vimeo.com' || $video['host'] == 'vimeo.com' ) {
$video_id = explode( '/', $url );
$video['id'] = $video_id[3];
$video['embed'] = '<iframe src="//player.vimeo.com/video/' . $video['id'] . '?title=0&byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
// Get thumbnail
$video['embed_url'] = '//player.vimeo.com/video/' . $video['id'] . '?title=0&byline=0&portrait=0&autoplay=1';
if ( ! $video_thumbnail ) {
$video_thumbnail = wp_remote_get( 'http://vimeo.com/api/v2/video/' . $video['id'] . '.json' );
if ( $video_thumbnail === FALSE ) {
$video_thumbnail = 'null';
}
}
$video_body = json_decode( $video_thumbnail['body'] );
$video['thumbnail'] = $video_body[0]->thumbnail_large;
$data = array(
'id' => $video['id'],
'hash' => 'px-' . rand(1, 100) . '-' . $video['id'],
'thumbnail' => $video['thumbnail'],
'thumbnail_small' => $video['thumbnail'],
'embed_url' => $video['embed_url']
);
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment