Mendapatkan jumlah dan membatasi kata dalam postingan WordPress

Jika Anda menggunakan Shortcode dalam postingan, terkadang untuk medapatkan jumlah dan membatasi kata dalam postingan WordPress dengan tepat, kita agak kesulitan. Berikut ini adalah function yang bisa Anda tambahkan dalam file functions.php theme Anda, dalam kode sudah diberikan penjelasan dan cara penggunaan.

add_filter( 'wp_trim_words', 'jv_trim_words', 10, 4 );
/* Trims text to a certain number of words.
 *
 * Kepp shortcode if exist in text.
 * Combination function of strip_shortcodes and wp_trim_words
 * Default $num_words = 55
 *
 ** USAGE
 ** Using directly
 ** jv_trim_words( $text, 56 )
 ** jv_trim_words( $text, 56, null, false, false, true ) – return array
 ** Shortcode hidden if $num_words is not set or if set with value = 55 with 4 arguments
 **
 ** Use wp_trim_words
 ** wp_trim_words( $text, $num_words = 56 )
 ** Fire wp_trim_words
 ** Shortcode hidden if $num_words is not set or $num_words = 55
 ** Position always in bottom
 ** add_filter( 'wp_trim_words', 'jv_trim_words', 10, 4 );
 *
 * @param  string  $text             Text to trim.
 * @param  int     $num_words        The number of words to trim the text to. Default 5.
 * @param  string  $more             An optional string to append to the end of the trimmed text, e.g. ….
 * @param  string  $original_content The text before it was trimmed.
 * @param  string  $pos              Shortcode Position. You can set 'top' value if using directly
 * @param  boolean $count            Get word count
 * @return string  The text after the filter witch $num_words
 * @return array   If using directly and parameter $count set to true
 */
function jv_trim_words( $text, $num_words = 55, $more = null, $original_content = false, $pos = false, $count = false ) {
	if ( null === $more)
		$more = ' ' . '[…]';

	$shortcode = $strip_shortcode = true;

	if ( ! $original_content )
		$original_content = $text;

	$text = $original_content;

	/* Check existing shortcode
	 *
	 */
	if ( false === strpos( $text, '[' ) )
		$strip_shortcode = false;

	global $shortcode_tags;

	if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) )
		$strip_shortcode = false;

	/* Strip content from shortcode
	 *
	 */
	if ( $strip_shortcode ) {
		preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $text, $matches );
		$tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );

		if ( ! empty( $tagnames ) ) {
			$text = do_shortcodes_in_html_tags( $text, true, $tagnames );
			$pattern = get_shortcode_regex( $tagnames );
			preg_match_all( "/$pattern/", $text, $match );

			if ( ! empty( $match[0] ) && is_array( $match[0] ) ) {
				$shortcode = '';
				$length    = count( $match[0] );
				for ( $i = 0 ; $i < $length; $i++ )
					$shortcode .= do_shortcode( $match[0][ $i ] ); //match shortcode
			}

			$text = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $text );
			$text = unescape_invalid_shortcodes( $text );
		}
	}

	/* Hide shortcode
	 * Base on count function arguments
	 *
	 */
	if ( func_num_args() == 1 || ( func_num_args() == 4 && 55 == $num_words ) )
		 $shortcode = '';

	/* Split content into array words
	 *
	 */
	$text = wp_strip_all_tags( $text );

	/*
	 * translators: If your word count is based on single characters (e.g. East Asian characters),
	 * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
	 * Do not translate into your own language.
	 */
	if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
		$text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
		preg_match_all( '/./u', $text, $words_array );
		$limit_words_array = array_slice( $words_array[0], 0, $num_words + 1 );
		$full_words_array  = $words_array[0];
		$sep = '';
	} else	{
		$limit_words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
		$full_words_array  = explode( ' ', preg_replace( "/[\n\r\t ]+/", ' ', $text ) );
		$sep = ' ';
	}

	/* Check word count base on $num_words
	 *
	 */
	$word_count = count( $full_words_array );
	if ( $word_count >= $num_words ) {
		array_pop( $limit_words_array );
		$text  = implode( $sep, $limit_words_array );
		$text .= $more;

		/* keep shortcode if exists and set position ( top or bottom text )
		 *
		 */
		switch( $pos )	{
			case 'top' :
				$text = $shortcode . $text;
				break;

			default :
				$text .= $shortcode;
				break;
		}
	} else {
		$text = apply_filters( 'the_content', $original_content );
	}

	if ( $count )
		return array(
			'text'  => $text,
			'count' => $word_count
		);

	return $text; //output
}

Cara kerja function ini sama dengan function the_excerpt atau get_the_excerpt, hanya saja kita tetap menampilkan shortcode ketika postingan melebihi batas kata yang kita tentukan. Kode shortcode dan kode html tidak dihitung.

Kode ini juga di sini Trim content and limit with certain count word.

Modifikasi Kolom Komentar WordPress Menjadi WYSIWYG Editor

Tanpa harus menggunakan plugin, Anda bisa memodifikasi sendiri kolom pesan atau komentar untuk blog WordPress Anda menjadi bentuk WYSIWYG Editor.

Modifikasi ini memanfaatkan function wp_editor dan menggunakan filter comment_form_defaults untuk menimpa kolom komentar yang lama. Berikut kode PHP yang harus Anda tambahkan di file functions.php theme Anda.

add_filter( 'comment_form_defaults','jv_comment_form');
function jv_comment_form( $args ) {
	$editor_id = 'comment'; // element id of textarea comment field

	$settings  = array(
		'editor_height'    => 50, //column height
		'media_buttons'    => false,
		'textarea_name'    => $editor_id,
		'teeny'            => true,
		'tinymce'          => array(
			'resize'                => true,
			'wordpress_adv_hidden'  => true,
			'add_unload_trigger'    => true,
			'statusbar'             => true,
			'autoresize_min_height' => 50,
			'wp_autoresize_on'      => true,
			'toolbar1'              => 'bold,italic,bullist,numlist'
		),
		'quicktags' => array( 'buttons' => 'strong, em, link, block, del, ins, img, ul, ol, li, code, more, close' )
	);

	if ( function_exists( 'wp_editor' ) )	{
		ob_start();
		wp_editor( '', $editor_id, $settings );
		$args['comment_field'] = ob_get_clean();

		return $args;
	}
}

Hasilnya seperti gambar berikut:

WP Editor Kolom Komentar
WP Editor Kolom Komentar

Extended Related Posts Plugin WordPress

Extended Related Posts (EXTRP) adalah plugin untuk blog WordPress yang fungsinya menampilkan pos terkait yang relevan dan lebih baik. Support dengan plugin Relevanssi untuk menampilkan related post sesuai algoritma plugin Relevanssi.

Fitur Plugin

  • Otomatis, tersedia pengaturan untuk tampilan di bawah postingan secara otomatis.
  • Excerpt, bentuk post excerpt/deskripsi tersedia dalam dua pilihan, default dan snippet.
  • Thumbnail, jika fitur ini diaktifkan, maka gambar diambil otomatis berdasarkan feature image, gambar dari pos, gambar pertama, dan jika tidak gambar dalam pos, maka akan tampil gambar default. Anda dapat menggunakan gambar default Anda sendiri, selain yang telah disediakan oleh plugin ini. Tersedia juga pilihan jika ingin mengambil gambar dengan url eksternal yang dalam pos, jika pos tersebut tidak memiliki gambar selain gambar eksternal. Ukuran thumbnail akan berubah secara otomatis sesuai dengan pengaturan ukuran thumbnail Anda dan Anda juga dapat menambahkan dengan ukuran yang baru.
  • Style, tersedia 7 jenis model tampilan related post.
  • Highlight keyword, memberikan sorotan pada kata kunci yang terdapat dalam deskripsi pos, tersedia 7 pilihan.
  • Widgets, tersedia pengaturan dalam widget untuk ditampilkan di sidebar situs Anda.
  • Shortcode Generator, Anda tidak perlu mengetikkan satu persatu parameter yang akan ditambahkan dalam shortcode related post. Dengan Shortcode Generator, Anda hanya memilih parameter dan nilainya untuk membuat shortcode sekaligus Kode PHP untuk dipasang di post area, widget atau di theme.
  • Kode PHP related post, jika theme Anda tidak memungkinkan untuk menampilkan related post secara otomatis, tersedia kode PHP yang dihasilkan dengan menggunakan Shortcode Generator.
  • Algoritma, plugin ini mencari pos yang berkaitan berdasarkan judul atau konten postingan, jika tidak ada, maka secara otomatis akan mencari berdasarkan kategori, tag, dan tiap kata dalam judul pos. Plugin Extended Related Posts dapat didukung oleh plugin Relevanssi untuk menampilkan pos terkait sesuai algoritma plugin Relevanssi.
  • Stopwords Filter, filter kata kunci yang tidak diinginkan untuk menampilkan pos terkait yang lebih relevan.
  • Caching, fitur ini untuk memberikan page load dan performa situs yang lebih baik dalam menampilkan pos terkait. Mekanisme cache sifatnya transient, dan tersimpan di database. Tersedia penjadwalan dan tombol untuk menghapus cache.
  • Multi-language, saat ini masih tersedia 2 bahasa, yaitu bahasa Inggris dan Indonesia.
  • Automatic update, update plugin dilakukan via GitHub. Sekarang tersedia di repositori plugin WordPress.

Screenshot plugin

General Settings
General Settings

Thumbnail Settings
Thumbnail Settings
Additional Settings
Additional Settings
Shortcode Generator
Shortcode Generator
Widget Settings
Widget Settings

Filter Hooks

Plugin EXTRP ( Extended Related Posts ) menyediakan beberapa fungsi filter hook untuk memodifikasi plugin ini.

extrp_capability_filter( $option )
extrp_limit_count_id( $limit )
extrp_wp_query( $args )
extrp_get_the_post_thumbnail( $get_attachment_link, $post_id, $size , $crop , $img_class )
extrp_default_settings( $args )

Update 24 Oktober 2015
Download Extended Related Posts
https://wordpress.org/plugins/extended-related-posts/
Please update your plugin via WordPress.

Bing Search Image API Azure Format Json PHP

Format xml search image dengan Bing API lawas yang gratis alias free, sudah tidak berlaku. Yang dipakai sekarang Bing API V.2 atau dengan Windows Azure Markerplace, masih ada yang gratis walaupun terbatas (limit) hanya sampai 5000 request. Dengan menggunakan format Bing Windows Azure, kita dapat melakukan parsing PHP yang sederhana untuk Bing Search Image format json dengan cara berikut:

Membuat Form Search Box

<form method="get" action="<?php echo $_SERVER['PHP_SELF'];?>">
	Type in a search:
<input type="text" id="searchText" name="s"
	value="<?php
		if (isset($_GET['s']))
		{
			echo($_GET['s']);
		}
			else
		{
			echo('superman');
		}
?>"/>
<input type="submit" value="Search" id="searchButton" />
</form>

Menampilkan hasil pencarian gambar berdasarkan kata kunci (keyword) yang ditentukan.

if (isset($_GET['s'])) {
	$accountKey = 'your-account-key-here'; //get it here https://datamarket.azure.com/account
	$ServiceRootURL =  'https://api.datamarket.azure.com/Bing/Search/';
	$count = 2;//total list
        $skip  = 0; //for paged
        $WebSearchURL = $ServiceRootURL . 'Image?$format=json&$top=' . $count . '&$skip=' . $skip . '&Query=';
	$context = stream_context_create(array(
		'http' => array(
		'request_fulluri' => true,
		'header'  => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
			)
	));
	$request = $WebSearchURL . urlencode( '\'' . $_GET['s'] . '\'');
	$response = file_get_contents($request, 0, $context);
	$jsonobj = json_decode($response);

	echo('<ul id="result">');
	foreach($jsonobj->d->results as $value)
	{
		echo('<li class="resultlistitem">');
		echo('<b>Title</b>: ' . $value->Title .'<br>');
		echo('<b>Url</b>: ' . $value->MediaUrl .'<br>');
		echo('<b>Source</b>: ' . $value->SourceUrl .'<br>');
		echo('<b>Display Url</b>: ' . $value->DisplayUrl .'<br>');
		echo('<b>Width</b>: ' . $value->Width .' px<br>');
		echo('<b>Height</b>: ' . $value->Height .' px<br>');
		echo('<b>File Size</b>: ' . KByteSize($value->FileSize) .'<br>');
		echo('<b>Image Type</b>: ' . $value->ContentType .'<br>');
		echo('<b>Thumbnail Url</b>: ' . $value->Thumbnail->MediaUrl . '<br>');
		echo('<b>Thumbnail Display</b>:<br><img src="' . $value->Thumbnail->MediaUrl. '"><br>');
		echo('<b>Large Image Display</b>:<br><img src="' . $value->MediaUrl. '">');
		echo('</li>');
	}
	echo("</ul>");
}

//function to convert file size image
function KByteSize($bytes) {
    $size = $bytes / 1024;
    if($size < 1024)
        {
        $size = number_format($size, 2);
        $size .= ' KB';
        }
    else
        {
        if($size / 1024 < 1024)
            {
            $size = number_format($size / 1024, 2);
            $size .= ' MB';
            }
        else if ($size / 1024 / 1024 < 1024)
            {
            $size = number_format($size / 1024 / 1024, 2);
            $size .= ' GB';
            }
        }
    return $size;
}

Tampilannya seperti gambar ini

Bing Image Api
Tampilan API Bing Search Image

Pastikan Anda mencantumkan Primary/Account Key Anda dalam kode tersebut, silahkan daftar di Windows Azure https://datamarket.azure.com/account, gratis terbatas. Semoga bermanfaat.

Reference Code
Migrating Bing Search API Applications

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

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 &#8211; 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 &#8211; 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 &#8211; 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.