Kode PHP – Search List dan Video YouTube Data API v.3

Kode PHP YouTube Data API 3 yang sederhana untuk menampilkan video hasil pencarian kata kunci dan video id.

Kode API youtube versi 1 tidak dapat digunakan lagi, untuk versi terbarunya yaitu YouTube Data API Version 3. Cara mudah untuk menampilkan daftar video Youtube berdasarkan kata kunci dan id video di situs atau aplikasi Anda, bisa dengan function PHP yang sederhana seperti ini:

Kode untuk menampilkan hasil

Search List
Untuk menampilkan video dari hasil pencarian berdasarkan kata kunci yang Anda tentukan.

jv_youtube('YOUR KEYWORD');

Single Video
Untuk menampilkan single video berdasarkan video id yang ditentukan. Cara mengetahui video id, misalnya pada link video YouTube https://www.youtube.com/watch?v=QqzekYZdBEo,
kode acak dalam link seperti ini QqzekYZdBEo adalah video id-nya.

jv_youtube('VIDEO ID','video');

Kombinasi dengan Form Search Box

$query = $_GET['x'];
echo '<form>
			<select name="type">
				<option value="search">List</option>
				<option value="videos">Video</option>
			</select>
			<input type="text" name="x" class="form-control" placeholder="Type Keywords or Video ID" value="'.$query.'" required>
			<button type="submit">SUBMIT</button>
	  </form>';
if(isset($query)){
	switch($_GET['type']){
		case 'videos';
			jv_youtube($query,'videos');
		break;
		default:
			jv_youtube($query);
		break;
	}
}

Kode function PHP YouTube API V.3

Simpan kode function berikut di bawah salah satu kode di atas atau di file khusus functions theme atau template situs Anda.

/**
 * Simple PHP Youtube Data API V.3
 * Code @jevuska https://www.jevuska.com/
 * Reference https://developers.google.com/youtube/v3/
 ***
 * USAGE
 ***
 * Search list function: jv_youtube('YOUR KEYWORD');
 * Single video function: jv_youtube('VIDEO ID','video');
 ***
 * With form query parameter 'x':
$query = $_GET['x'];
echo '<form>
			<select name="type">
				<option value="search">List</option>
				<option value="videos">Video</option>
			</select>
			<input type="text" name="x" class="form-control" placeholder="Type Keywords or Video ID" value="'.$query.'" required>
			<button type="submit">SUBMIT</button>
	  </form>';
if(isset($query)){
	switch($_GET['type']){
		case 'videos';
			jv_youtube($query,'videos');
		break;
		default:
			jv_youtube($query);
		break;
	}
}
 */

function jv_youtube_setup(){
	//setup Google API Key, create here https://console.developers.google.com/project/
	define('GOOGLE_API_KEY', 'your-google-api-key-here');
	
	//setup PART video api data - allowed values: [snippet,contentDetails,statistics,status]
	define('PART_VIDEO_DATA', 'snippet,contentDetails,statistics,status');
	define('PART_SEARCH_LIST_DATA', 'snippet');

	//setup as 'true' or 'false' to show Video Details and Statistics
	define('VIDEO_DETAILS',true);
	define('VIDEO_STATS', true);
	define('PLAYER', true);

	//setup search list - optional
	define('MAX_RESULT', '5'); //list file per page, min default is 5, max is 50
	define('SEARCH_TYPE', 'video'); //video, channel, playlist
	define('LIST_ORDER', 'date'); //date, rating, relevance, title, videocount, viewcount
	define('SAFE_SEARCH', 'moderate'); //moderate, strict, none

	//setup your text
	define('TOTAL_RESULT', 'Total Results:');
	define('RESULT_PER_PAGE', 'Results Per Page:');
		//write cacheing logic to implement this feature, ie: CACHE LITE PHP
			// define( 'NEXT_PAGE_TOKEN', 'Next Page Token:' ); 
			// define( 'PREVIOUS_PAGE_TOKEN', 'Previous Page Token:' );
	define('VIDEO_TITLE', 'Title:');
	define('VIDEO_DESCRIPTION', 'Description:');
	define('VIDEO_ID', 'Video Id:' );
	define('LINK_VIDEO', 'Link Video:');
	define('CHANNEL_TITLE', 'Channel Title:');
	define('CHANNEL_ID', 'Channel Id:');
	define('LINK_CHANNEL', 'Link Channel:');
	define('VIDEO_THUMBNAIL', 'Thumbnail:');
	define('VIDEO_PLAYER', 'Video Player:');
	define('TIME_PUBLISH', 'Published:');
	define('VIDEO_DURATION', 'Duration:');
	define('VIDEO_DIMENSION', 'Dimension:');
	define('VIDEO_DEFINITION', 'Definition:');
	define('VIDEO_CAPTION', 'Caption:');
	define('VIDEO_LICENSE', 'License:');
	define('COUNT_VIDEO_VIEW', 'View:');
	define('COUNT_VIDEO_LIKE', 'Like:');
	define('COUNT_VIDEO_DISLIKE', 'Dislike:');
	define('COUNT_VIDEO_FAVORITE', 'Favorite:');
	define('COUNT_VIDEO_COMMENT', 'Comment:');
}

function _jv_youtube_data($q,$type=''){
	jv_youtube_setup();
	switch($type){
		case 'videos':
			$data = array(
				'key' => GOOGLE_API_KEY,
				'id' => $q, //video id
				'part' => PART_VIDEO_DATA,
				//MORE OPTION https://developers.google.com/youtube/v3/
			);
		break;
		default:
			$type = 'search';
			$data = array(
				'key' => GOOGLE_API_KEY,
				'q' => urlencode($q), //query search parameter
				'part' => PART_SEARCH_LIST_DATA,

				//START OPTIONAL - comment this rest option if not used (add //)
				'maxResults' => MAX_RESULT,
				'type' => SEARCH_TYPE,
				'order' => LIST_ORDER,
				'safeSearch' => SAFE_SEARCH,
				//END OPTIONAL
				//MORE OPTION https://developers.google.com/youtube/v3/docs/search/list
			);
		break;
	}

	$param = http_build_query($data);
	$json = "https://www.googleapis.com/youtube/v3/$type?$param";
	$str = @file_get_contents($json);
	return $str;
}

function jv_youtube($q, $type = '',$inline = ''){
	$result = '';
	$str = _jv_youtube_data($q, $type);
	if($str === FALSE)	:
		// error handling
		$msg = "Invalid parameter file_get_contents";
		$result .= sprintf('%s', $str);
	else :
		$result .= _jv_search_youtube($str, $type, $inline);
	endif;
	
	if($inline == 'inline')
		return $result;
	else
		print $result;
}

function _jv_search_youtube($str, $type, $inline){
	$doc = json_decode($str, true);
	$respon = array();
	
	$totalresult = (int) $doc['pageInfo']['totalResults'];
	$resultsperpage = (int) $doc['pageInfo']['resultsPerPage'];

	if(empty($inline)){
		if ( defined( 'TOTAL_RESULT' ) )
		$respon[] = sprintf('<b><b>%1$s</b></b> %2$s',TOTAL_RESULT,$totalresult);
		if ( defined( 'RESULT_PER_PAGE' ) )
		$respon[] = sprintf('<b>%1$s</b> %2$s',RESULT_PER_PAGE,$resultsperpage);
	}
	if(empty($type)){
		$nextpage =  $doc['nextPageToken'];
		$prevpage =  $doc['prevPageToken'];
		
		if ( defined( 'NEXT_PAGE_TOKEN' ) )
		$respon[] =  sprintf('<b>%1$s</b> %2$s',NEXT_PAGE_TOKEN,$nextpage);
		if ( defined( 'PREVIOUS_PAGE_TOKEN' ) )
		$respon[] =  sprintf('<b>%1$s</b> %2$s',PREVIOUS_PAGE_TOKEN,$prevpage);
	}
	$i = 0;
	foreach($doc['items'] as $item) {
		$i++;
		if(empty($inline)){
			$title = $item['snippet']['title']; //video title
			$description = $item['snippet']['description']; //video description
			
			$published = $item['snippet'] ['publishedAt']; //published time
			//date format http://php.net/manual/en/datetime.formats.date.php
			$datepublish = date('d-m-Y',strtotime($published));
			
			$videoid = '';
			if(isset($item['id']['videoId']))
				$videoid .= $item['id']['videoId'];
			else
				$videoid .= $item['id'];
			$video_url = "https://www.youtube.com/watch?v=$videoid"; //video url
			$channelid = $item['snippet'] ['channelId']; //channel id
			$thumbnail_url = $item['snippet']['thumbnails']['medium']['url'];//thumbnail option: Allowed values: [default, medium, high]
			$channel_url = "https://www.youtube.com/channel/$channelid"; //channel url
			
			$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_TITLE,$title);
			$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_DESCRIPTION,$description);
			if ( defined( 'VIDEO_ID' ) )
				$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_ID,$videoid);
			if ( defined( 'CHANNEL_ID' ) )
				$respon[] = sprintf('<b>%1$s</b> %2$s',CHANNEL_ID,$channelid);
			if ( defined( 'TIME_PUBLISH' ) )
				$respon[] = sprintf('<b>%1$s</b> %2$s',TIME_PUBLISH,$datepublish);
			if ( defined( 'VIDEO_THUMBNAIL' ) )
				$respon[] = sprintf('<b>%1$s</b><br><img src="%2$s">',VIDEO_THUMBNAIL,$thumbnail_url);
			if ( PLAYER == true )
				$respon[] = sprintf("<b>%s</b><br><div id='player-$i' class='player' data-id='$videoid'></div>",VIDEO_PLAYER);
			if ( defined( 'LINK_VIDEO' ) )
				$respon[] = sprintf('<b>%1$s</b> <a href="%2$s">%2$s</a>',LINK_VIDEO,$video_url);
			if ( defined( 'LINK_CHANNEL' ) )
				$respon[] = sprintf('<b>%1$s</b> <a href="%2$s">%2$s</a>',LINK_CHANNEL,$channel_url);
		}
		
		if($type == 'videos'){
			$channelititle = $item['snippet'] ['channelTitle']; //channel title
			if ( defined( 'CHANNEL_TITLE' ) )
				$respon[] = sprintf('<b>%1$s</b> %2$s',CHANNEL_TITLE,$channelititle);
			$details = $item['contentDetails'];
			$statistics = $item['statistics'];
			if ( VIDEO_DETAILS == true){
				foreach( array($details) as $item ) {
					$duration = covtime($item['duration']);
					$dimension = $item['dimension'];
					$definition = $item['definition'];
					$caption = $item['caption'] != 'false' ? $item['caption']: '-';
					$license = $item['licensedContent'];
					if ( defined( 'VIDEO_DURATION' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_DURATION,$duration);
					if ( defined( 'VIDEO_DIMENSION' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_DIMENSION,$dimension);
					if ( defined( 'VIDEO_DEFINITION' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_DEFINITION,$definition);
					if ( defined( 'VIDEO_CAPTION' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_CAPTION,$caption);
					if ( defined( 'VIDEO_LICENSE' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_LICENSE,$license);
				}
			}
		
			if ( VIDEO_STATS == true ){
				foreach( array($statistics) as $item ) {
					$view = $item['viewCount'];
					$like = $item['likeCount'];
					$dislike = $item['dislikeCount'];
					$favorite = $item['favoriteCount'];
					$comment = $item['commentCount'];
					if ( defined( 'COUNT_VIDEO_VIEW' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_VIEW,$view);
					if ( defined( 'COUNT_VIDEO_LIKE' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_LIKE,$like);
					if ( defined( 'COUNT_VIDEO_DISLIKE' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_DISLIKE,$dislike);
					if ( defined( 'COUNT_VIDEO_FAVORITE' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_FAVORITE,$favorite);
					if ( defined( 'COUNT_VIDEO_COMMENT' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_COMMENT,$comment);
				}
			}
			$respon[] = '<hr>';	
		}
		if(empty($type))
			$respon[] = jv_youtube($videoid,'videos','inline');
	}
	$result = implode('<br>',$respon);
	return $result;
}

function covtime($youtube_time) {
	//function convert youtube time. Source: http://stackoverflow.com/questions/24393230/convert-youtube-api-v3-video-duration-in-php
    preg_match_all('/(\d+)/',$youtube_time,$parts);
    if (count($parts[0]) == 1) {
        array_unshift($parts[0], "0", "0");
    } elseif (count($parts[0]) == 2) {
        array_unshift($parts[0], "0");
    }

    $sec_init = $parts[0][2];
    $seconds = $sec_init%60;
    $seconds_overflow = floor($sec_init/60);

    $min_init = $parts[0][1] + $seconds_overflow;
    $minutes = ($min_init)%60;
    $minutes_overflow = floor(($min_init)/60);

    $hours = $parts[0][0] + $minutes_overflow;

    if($hours != 0)
        return $hours.':'.$minutes.':'.$seconds;
    else
        return $minutes.':'.$seconds;
}

Berikut kode JavaScript jika ingin menampilkan video player secara asyncronous.

<script>
//https://developers.google.com/youtube/iframe_api_reference
//http://stackoverflow.com/a/901144
	var tag = document.createElement('script');

	tag.src = "https://www.youtube.com/iframe_api";
	var firstScriptTag = document.getElementsByTagName('script')[0];
	firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    players = new Array();
	var player = document.getElementsByClassName('player');
	function onYouTubeIframeAPIReady() {
		for (var i = 0; i < player.length; i++) {
			t = new YT.Player(player[i].getAttribute('id'), {
				height: '390',
				width: '640',
				videoId: player[i].getAttribute('data-id'),
				events: {
					//'onReady': onPlayerReady,
					'onStateChange': onPlayerStateChange
				}
			});
			players.push(t);
		}
	}

	function onPlayerReady(event) {
		event.target.playVideo();
	}

	function onPlayerStateChange(event) {
		var temp = event.target.getVideoUrl();
		if (event.data == YT.PlayerState.PLAYING) {
			for (var i = 0; i < players.length; i++) {
              if (players[i].getVideoUrl() != temp) {
				  setTimeout(players[i].stopVideo, 6000);
				  players[i].stopVideo();
			  }
			}
        }
	}

	function getParameterByName(name) {
		name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
		var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
			results = regex.exec(location.search);
		return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
	}
</script>

Set-up Google API Key Anda (ganti your-google-api-key-here pada kode function di atas), petunjuk tambahan lainnya ada dalam kode tersebut.

Youtube API 3 Search List Demo
Tampilan Script PHP Youtube API 3 Search

Kode PHP Video YouTube Data API v.3 ini tidak menggunakan Google Client API PHP library, jadi cukup sederhana untuk Anda terapkan di situs seperti WordPress atau aplikasi Anda. Kode untuk tampilan dan referensi lainnya bisa temukan di Google Developer YouTube Data API. Semoga bermanfaat.


 Share

API YouTube Search + fancyBox jQuery di WordPress

Tutorial penggunaan API YouTube Search digabungkan dengan fancyBox jQuery yang diterapkan di halaman pencarian WordPress (WordPress Search Results Page).

Sebelumnya sudah dibahas PHP API Video YouTube yang paling sering dilihat (Top Rated), kali ini adalah tutorial penggunaan API YouTube Search digabungkan dengan fancyBox jQuery yang diterapkan di halaman pencarian WordPress (WordPress Search Results Page). Versi API YouTube yang digunakan dalam tutorial ini adalah versi 2, sedangkan versi 3 masih dalam experimental. Kombinasi dengan FancyBox jQuery di sini berguna untuk menampilkan player video YouTube dalam bentuk window pop-up ketika gambar diklik.

Cara implementasinya sebagai berikut:

  1. Download file api-youtube-fancybox-media.zip (Kode PHP API YouTube Search + fancyBox jQuery) di sini.
  2. Extrak file zip tersebut, dan simpan folder dengan nama fancymedia di root theme WP Anda.
  3. Pasang kode berikut di header.php sebelum kode </head>
    <script type="text/javascript" src="<?php bloginfo( 'template_url' ); ?>/fancymedia/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="<?php bloginfo( 'template_url' ); ?>/fancymedia/jquery.fancybox.pack.js"></script>
    <script type="text/javascript" src="<?php bloginfo( 'template_url' ); ?>/fancymedia/jquery.fancybox-media.js"></script>
    <link rel="stylesheet" type="text/css" href="<?php bloginfo( 'template_url' ); ?>/fancymedia/jquery.fancybox.css" media="screen" />
    <script type="text/javascript" src="<?php bloginfo( 'template_url' ); ?>/fancymedia/fb.setting.js"></script>
    
  4. Simpan kode API YouTube dalam file php-yt.php di search.php. Kode PHP API YouTube seperti ini:
    <form method="get" action="<?php echo trailingslashit( home_url() ); ?>">
          <input class="input" type="text" name="s" value="<?php if ( is_search() ) echo esc_attr( get_search_query() ); else esc_attr_e( 'Search Video...'); ?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
          <select name="o">
          <option value="relevance">Relevance</option>
          <option value="published">Publication time</option>
          <option value="viewCount">User views</option>
          <option value="rating">User rating</option>
          </select>
          <select name="i">
            <option value="10">10</option>
            <option value="25">25</option>
            <option value="50">50</option>
            <option value="100">100</option>
          </select>
          <input type="submit" value="search"/>  
    </form>
     <?php
          if (!isset($_GET&#91;'s'&#93;) || empty($_GET&#91;'s'&#93;)) {
            die ('ERROR: Please enter one or more search keywords');
          } else {
            $s = $_GET&#91;'s'&#93;;
            $s = ereg_replace('&#91;&#91;:space:&#93;&#93;+', ' ', trim($s));
            $s = urlencode($s);
          }
          if (!isset($_GET&#91;'o'&#93;) || empty($_GET&#91;'o'&#93;)) {
            $o = 'viewCount';
          } else {
            $o = htmlentities($_GET&#91;'o'&#93;);
          }
          if (!isset($_GET&#91;'i'&#93;) || empty($_GET&#91;'i'&#93;)) {
            $i = 25;
          } else {
            $i = htmlentities($_GET&#91;'i'&#93;);
          }
          if (!isset($_GET&#91;'pageID'&#93;) || $_GET&#91;'pageID'&#93; <= 0) {
            $t = 1;  
          } else {        
            $pageID = htmlentities($_GET&#91;'pageID'&#93;);
            $t = (($pageID-1) * $i)+1;  
          }
    
    
        // Setting URL Feed
        $ytfeedURL = 'https://gdata.youtube.com/feeds/api/videos?q='.$s.'&orderby='.$o.'&max-results='.$i.'&start-index='.$t.'&v=2';
        $ytxml = simplexml_load_file($ytfeedURL);
        ?>
          <h1><?php echo $ytxml->title; ?></h1>
        <?php
        foreach ($ytxml->entry as $entry) {
          $media = $entry->children('http://search.yahoo.com/mrss/');
          $attrs = $media->group->player->attributes();
          $watch = $attrs['url']; 
          $attrs = $media->group->content->attributes();
          $player = $attrs['url']; 
          $attrs = $media->group->thumbnail[2]->attributes();
          $thumbnail = $attrs['url']; 
          $yt = $media->children('http://gdata.youtube.com/schemas/2007');
          $attrs = $yt->duration->attributes();
          $length = $attrs['seconds']; 
          $yv = $entry->children('http://gdata.youtube.com/schemas/2007');
          if ($yv->statistics) {
            $attrs = $yv->statistics->attributes();
            $viewCount = $attrs['viewCount']; 
          } else {
            $viewCount = 0; 
          } 
         
          $gd = $entry->children('http://schemas.google.com/g/2005'); 
          if ($gd->rating) {
            $attrs = $gd->rating->attributes();
            $rating = $attrs['average']; 
          } else {
            $rating = 0; 
          } 
          ?>
          <div class="item">
            <span class="title">
              <a class="fancybox-media" href="<?php echo $watch; ?>"><?php echo $media->group->title; ?></a>
            </span>
    
            <p><?php echo $media->group->description; ?></p>
            <p>
              <span class="thumbnail">
                <a class="fancybox-media" href="<?php echo $player; ?>"><img src="<?php echo $thumbnail;?>" /></a>
                <br/>
                Click to play
                <br/>
              </span>
    <span class="attr">Duration:</span> <?php printf('%0.2f', $length/60); ?> min. | <span class="attr">Rating:</span> <?php echo $rating; ?> | <span class="attr">Views:</span> <?php echo $viewCount; ?> | <span class="attr">By:</span> <?php echo $entry->author->name; ?>        
            </p>
          </div>      
        <?php
        }
        ?>
    
  5. Save pekerjaan Anda.

Tampilannya seperti gambar berikut:

Keyword Search API YouTube
Keyword Search API YouTube

FancyBox Media API YouTube
FancyBox Media

Deskripsi

  • Dalam kode kode PHP API YouTube, terdapat kode class=”fancybox-media”, fungsinya untuk fancyBox media player YouTube pada saat diklik.
  • Disable klik kanan untuk gambar dan setting ukuran (width/height) fancyBox player YouTube terdapat pada file fb.setting.js.
  • Anda bisa menerapkan tutorial ini di platform lainnya selain WordPress dengan mengganti parameter url s dengan parameter url yang Anda inginkan.

Referensi

  • Dokumentasi API YouTube versi 2 ~ https://developers.google.com/youtube/2.0/reference
  • File FancyBox jQuery ~ http://fancybox.net/

PHP API Video YouTube yang paling sering dilihat

Tutorial ini memperkenalkan bagaimana ekstensi PHP merender data API YouTube yang digunakan untuk melihat video user-generated content yang paling sering dilihat dan mengakses metadata video.

Situs Sharing Video YouTube memungkinkan pengembang aplikasi web untuk mengakses konten publiknya melalui REST-based developer API. Ekstensi SimpleXML dalam PHP adalah fungsi yang sangat ideal untuk memproses feed XML yang dihasilkan dari API YouTube. Tutorial ini memperkenalkan bagaimana ekstensi PHP merender data API YouTube yang digunakan untuk melihat video user-generated content yang paling sering dilihat dan mengakses metadata video seperti deskripsi, judul, durasi dan rating video.

Beberapa standar feed YouTube yang sering digunakan oleh pengembang aplikasi adalah:

  1. Highly rated videos: http://gdata.youtube.com/feeds/api/standardfeeds/top_rated
  2. Most recently-added videos: http://gdata.youtube.com/feeds/api/standardfeeds/most_recent
  3. Most linked videos: http://gdata.youtube.com/feeds/api/standardfeeds/most_linked

Sekarang mari kita proses feed API YouTube tersebut dengan menggunakan PHP. Fungsi simplexml_load_file untuk mengekstrak fragmen yang relevan dari data feed dan memformatnya ke dalam halaman Web

  <?php
    // Setting URL Feed
    $ytfeedURL = 'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated';
    $ytxml = simplexml_load_file($ytfeedURL);
    ?>
      <h1><?php echo $ytxml->title; ?></h1>
    <?php
    foreach ($ytxml->entry as $entry) {
      $media = $entry->children('http://search.yahoo.com/mrss/');
      $attrs = $media->group->player->attributes();
      $watch = $attrs['url']; 
      $attrs = $media->group->content->attributes();
      $player = $attrs['url']; 
      $attrs = $media->group->thumbnail[2]->attributes();
      $thumbnail = $attrs['url']; 
      $yt = $media->children('http://gdata.youtube.com/schemas/2007');
      $attrs = $yt->duration->attributes();
      $length = $attrs['seconds']; 
      $yv = $entry->children('http://gdata.youtube.com/schemas/2007');
      if ($yv->statistics) {
        $attrs = $yv->statistics->attributes();
        $viewCount = $attrs['viewCount']; 
      } else {
        $viewCount = 0; 
      } 
      $viewCount = $attrs['viewCount']; 
      $gd = $entry->children('http://schemas.google.com/g/2005'); 
      if ($gd->rating) {
        $attrs = $gd->rating->attributes();
        $rating = $attrs['average']; 
      } else {
        $rating = 0; 
      } 
      ?>
      <div class="item">
        <span class="title">
          <a href="<?php echo $watch; ?>"><?php echo $media->group->title; ?></a>
        </span>
        <p><?php echo $media->group->description; ?></p>
        <p>
          <span class="thumbnail">
            <a href="<?php echo $player; ?>"><img src="<?php echo $thumbnail;?>" /></a>
            <br/>click to view
          </span>
          <span class="attr">By:</span> <?php echo $entry->author->name; ?> <br/>
          <span class="attr">Duration:</span> <?php printf('%0.2f', $length/60); ?> 
          min. <br/>
           <span class="attr">Rating:</span> <?php echo $rating; ?><br/>
           <span class="attr">Views:</span> <?php echo $viewCount ?>
        </p>
      </div>      
    <?php
    }
    ?>

Tampilan seperti gambar berikut:
Top Rated Video Youtube

Selanjutnya Anda dapat membuat CSSnya untuk membuat tampilannya lebih menarik.

UPDATED 04-09-2012

  • Menambahkan atribut player video YouTube
          $attrs = $media->group->content->attributes();
          $player = $attrs['url'];
    
  • Mengganti link thumbnail. Menjadi seperti ini:
    <a href="<?php echo $player; ?>"><img src="<?php echo $thumbnail;?>" /></a>
  • Anda dapat menambahkan iframe video YouTube. Kode iframe seperti ini:
    <iframe width="560" height="315" src="<?php echo $player; ?>" frameborder="0" allowfullscreen></iframe><
  • Jika Anda menginginkan landing page untuk frame video YouTube, cara gampangnya sebagai berikut:
    1. Buat Page Template khusus untuk halaman page dan beri nama misalnya, “YouTube Player Template“.
      (Cara membuat Page Template baca di sini → http://codex.wordpress.org/Pages#Creating_Your_Own_Page_Templates)
    2. Tempatkan kode berikut di area konten Page Template “YouTube Player Template“.
      <?php
      if ($ytplayer = $_GET['v']){
      echo  '<iframe width="560" height="315" src="'.$ytplayer.'" frameborder="0" allowfullscreen></iframe>';
      }else{
      echo  'No Video';
      }
      ?>
      

      Kode ini menggunakan parameter url “v“.

    3. Bikin halaman/page baru dan beri judul misalnya, “Watch“, dan permalinknya jadi seperti ini http//domain.ltd/watch. Pada Page Attribute, jangan lupa untuk memilih Page Template “YouTube Player Template” yang telah dibuat sebelumnya, lalu publish halaman tersebut.
    4. Ganti kode link thumbnail PHP API Video YouTube di atas (new update), menjadi seperti ini:
      <a target="_blank" rel="nofollow" href="<?php bloginfo('home') ?>/watch?v=<?php echo $player; ?>"><img src="<?php echo $thumbnail;?>" /></a>
    5. Save pekerjaan Anda, dan coba klik salah satu thumbnail, akan tampil landing page untuk player video YouTube. Contoh url landing page player video YouTube seperti ini:
      http//domain.ltd/watch?v=http://www.youtube.com/v/kn6-c223DUU?version=3&f=standard&app=youtube_gdata

UPDATED 18-09-2012

  • Menambahkan statistik views
          $yv = $entry->children('http://gdata.youtube.com/schemas/2007');
          if ($yv->statistics) {
            $attrs = $yv->statistics->attributes();
            $viewCount = $attrs['viewCount']; 
          } else {
            $viewCount = 0; 
          } 
    
  • Jika ingin mengganti landing page dengan fancyBox jQuery, Anda bisa baca tutorial API YouTube Search + fancyBox jQuery di WordPress.

Metode yang sama juga digunakan dalam tutorial Parsing xml user timeline & json search Twitter di WordPress.

UPDATE 12 Juli 2015
YouTube API dalam kode ini sudah tidak dapat digunakan. Silahkan gunakan versi terbaru PHP YouTube API 3.


 Bagikan