Skip to content

Instantly share code, notes, and snippets.

@hugosolar
Last active December 14, 2015 15:58
Show Gist options
  • Save hugosolar/5111310 to your computer and use it in GitHub Desktop.
Save hugosolar/5111310 to your computer and use it in GitHub Desktop.
Youtube video class for wordpress
<?php
/**
* Obtain youtube video API object and transients it
* eg. $video = new youtube_videos('simonscat');
* $video->get_videos(array('offset' => 5,'num_videos' => 10));
* @param $account string Account youtube name
* @return none
* @author Hugo Solar <contacto@hugosolar.net>
* */
class youtube_videos {
private static $instance;
private $num_videos;
public $account;
private $cache_time;
const data_type = 'json';
private $api_url;
public $data;
public function __construct($author) {
$this->set_api_url($author);
$this->set_cache_time(2);
if (false === get_transient('videoLoad-'.$author)) {
$this->get_data();
set_transient('videoLoad-'.$author,$this->data,60*60*$this->get_cache_time());
} else {
$this->data = get_transient( 'videoLoad-'.$author );
}
}
private function set_api_url($author) {
$this->account = $author;
$this->api_url = 'http://gdata.youtube.com/feeds/api/videos?alt='.self::data_type.'&author='.$this->account;
}
private function get_api_url() {
return $this->api_url;
}
private function set_cache_time($time) {
$this->cache_time = $time;
}
private function get_cache_time() {
return $this->cache_time;
}
private function get_data() {
$cache_time = $this->get_cache_time();
$api_url = $this->get_api_url();
$api_obj = new WP_Http;
$api_request = $api_obj->request($this->get_api_url());
$this->data = json_decode($api_request['body']);
$textVideo = $this->data;
return $textVideo;
}
public function get_videos($args=null) {
$s = wp_parse_args($args,array(
'offset' => 0,
'num_videos' => -1
));
extract($s);
$i = 0;
$video_list = array();
foreach ($this->data->feed->entry as $k => $video) {
if ( ($k >= $offset) ) {
if (($i < $num_videos)&&($num_videos != -1)) {
array_push($video_list, $video);
$i++;
} elseif($num_videos == -1) {
array_push($video_list, $video);
}
}
}
return $video_list;
}
function get_video_link($video) {
return $video->link[0]->href;
}
function get_video_id($video) {
return array_pop(explode('/',$video->{'id'}->{'$t'}));
}
function get_video_thumb($video,$size){
return $video->{'media$group'}->{'media$thumbnail'}[$size]->url;
}
function get_video_title($video){
return $video->{'media$group'}->{'media$title'}->{'$t'};
}
function get_video_time($video) {
return gmdate("H:i:s", $video->{'media$group'}->{'yt$duration'}->seconds);
}
function get_video_views($video) {
return $video->{'media$group'}->{'yt$statistic'}->viewCount;
}
function get_video_favorites($video) {
return $video->{'media$group'}->{'yt$statistic'}->favoriteCount;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment