I had been using a function I created after piecing together different bits of code for my WordPress blog. It allowed me to pass in a shortcode with a value defining the URL of the YouTube video, then it would print the embedded video, the view count and the duration immediately underneath it.
Unfortunately, it appears that the API I was using was depreciated by Google and I can’t seem to get the current API (v3) to work with this code, so I’d appreciate some help in trying to make this right. I grabbed a developer key from Google and am able to get the JSON response when I open it directly in my browser but it seems like the calls in the code below doesn’t want to match up for some reason. It would help if I still could reference the old API response to compare so I’m sort of flying blind here.
add_shortcode('yt', 'getYoutubeFrame');
// Convert Seconds to Minutes
function sec2hms ($sec, $padHours = false)
{
$hms = "";
$hours = intval(intval($sec) / 3600);
$hms .= ($padHours)
? str_pad($hours, 2, "0", STR_PAD_LEFT). ":"
: $hours. ":";
$minutes = intval(($sec / 60) % 60);
$hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";
$seconds = intval($sec % 60);
$hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
return $hms;
}
function getYoutubeFrame($atts) {
extract(shortcode_atts(array(
'video' => ''
), $atts));
// Get YouTube data via the API
$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos?q=$video&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'feed'}->{'entry'}[0]->{'yt$statistics'}->{'viewCount'};
$views = number_format($views);
$duration = $JSON_Data->{'feed'}->{'entry'}[0]->{'media$group'}->{'yt$duration'}->{'seconds'};
$s = "<iframe width="1280" height="720" src="//www.youtube.com/embed/$video?showinfo=0&rel=0&modestbranding=1&theme=light&iv_load_policy=3&autohide=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe>";
$s .= "<strong>Views:</strong> $views<br><strong>Duration:</strong> ";
$s .= sec2hms($duration);
$s .= "<br /><br />";
return $s;
}
It appears that the API has changed the way the duration is displayed (using ISO 8601 instead of raw number of seconds). My experience and knowledge of PHP is rather limited otherwise I probably could have solved this in my sleep! Any suggestions for how to resolve this?
You can use the videos:list call on v3 of the YouTube API like this:
This will get the number of views and the duration of the video specified in
$videoId
.The
$duration
is going to come back in ISO 8601 format which looks something likePT4H48M18S
. You can pass this into a DateInterval class and then format as you wish. For instance:would take
PT4H48M18S
and make it look like this04:48:18
.