Skip to content

Instantly share code, notes, and snippets.

@yurivictor
Last active July 7, 2017 07:28
Show Gist options
  • Save yurivictor/7144273 to your computer and use it in GitHub Desktop.
Save yurivictor/7144273 to your computer and use it in GitHub Desktop.
Get video information from url and convert to array
<?php
/**
* Get video information and convert to array
* @param string $url, the url of the video
* @uses wp_remote_get()
* @return array $video, information about the video
*/
function get_video( $url ) {
$video = array();
$split_url = parse_url( $url );
if ( isset( $split_url['host'] ) ) {
$video['host'] = $split_url['host'];
// Set up youtube variables
if ( $video['host'] == 'www.youtube.com' || $video['host'] == 'youtube.com' ) {
$video_id = explode( '?v=', $url ); // For videos like watch?v=...
if ( empty( $video_id[1] ) ) {
$video_id = explode( '&v=', $url ); // For videos like watch?player&v=
if ( empty( $video_id[1] ) ) {
$video_id = explode( '/v/', $url ); // For videos like watch/v/
}
}
$video_id = explode( '&', $video_id[1] ); // Deleting any other params
$video['id'] = $video_id[0];
$video['embed'] = '<iframe id="ytplayer" type="text/html" width="960" height="720" src="http://www.youtube.com/embed/' . $video['id'] . '?autoplay=0&enablejsapi=1&wmode=transparent" frameborder="0"></iframe>';
$video['thumbnail'] = 'http://img.youtube.com/vi/' . $video['id'] . '/0.jpg';
// Set up vimeo variables
} 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
global $memcache;
$video_thumbnail = $memcache->get( 'video-' . $video['id'] );
if ( ! $video_thumbnail ) {
$video_thumbnail = wp_remote_get( 'http://vimeo.com/api/v2/video/' . $video['id'] . '.json' );
if ( $video_thumbnail === FALSE ) {
$video_thumbnail = 'null';
}
$memcache->set( 'video-' . $video['id'], $video_thumbnail, MEMCACHE_COMPRESSED, 600000 );
}
$video_body = json_decode( $video_thumbnail['body'] );
$video['thumbnail'] = $video_body[0]->thumbnail_large;
}
// if all else fails, just return the embed
} else {
$video['embed'] = $url;
}
return $video;
}
@Kradre
Copy link

Kradre commented Jul 7, 2017

Thank you so much! Helped me alot with vimeo api.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment