Wordpress Shortcode to get Youtube Channel Views via YouTube API - php

I am Wordpress User and not the Programmer.
I want to create a shortcode in the functions.php to get the total views of any youtube channel.
I use the shortcode and give the channel ID Value. After the shortcode function gives back via YouTube API the current Channel Views of the given Channel ID.
In the YouTube Documentation, I found the following Code:
function channelsListById($service, $part, $params) {
$params = array_filter($params);
$response = $service->channels->listChannels(
$part,
$params
);
print_r($response);
}
channelsListById($service,
'statistics',
array('id' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw'));
}
The Response looks like that:
/**
* API response
*/
{
"kind": "youtube#channelListResponse",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/d9WwK8U1FuV6c-shZpzmnYUgGvQ\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/Psv3E9LCdk66gkF4HSIYK44crMI\"",
"id": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"statistics": {
"viewCount": "118283693",
"commentCount": "393",
"subscriberCount": "1165598",
"hiddenSubscriberCount": false,
"videoCount": "4435"
}
}
]
}
I think, I need to add some code to get the item field "viewCount" Value.
I don´t know if it is possible to do that, but I hope some of you Pros know the solution.
At the End of the Code, I just have to add:
add_shortcode( 'channel_views', 'shortcode_title' );
Would be amazing, if you could respond with the code I have to invert to the functions.php ;)
If you need more information to be able to respond, just ask me.

Use this plugin.
https://wordpress.org/plugins/youmax-channel-embeds-for-youtube-businesses/
This plugin simply gets all the videos from youtube channel in the grid format.

Related

retrieve the total likes and dislikes of a youtube channel using php

I am trying to get the total likes and dislikes of a company channel youtube using API and php but as for now I get only subscribers , total views, and total videos.Does anybody knows how can I proceed, I need to push all these informations to a DB.
"statistics": {
"viewCount": "793781",
"commentCount": "0",
"subscriberCount": "3861",
"hiddenSubscriberCount": false,
"videoCount": "149"
}
Look at the documentation : you can use the getRating endpoint like this :
GET https://www.googleapis.com/youtube/v3/videos/getRating
And you will get somethings like this
{
"kind": "youtube#videoGetRatingResponse",
"etag": etag,
"items": [
{
"videoId": string,
"rating": string
}
]
}

Youtube API - Get duration of videos from a playlist

I need to get the duration of all the videos in a Youtube playlist.
I know that the API does not show me the duration of each video when doing the search of all, but it does show it if the query is made for a particular video.
Through PHP I tried to collect all the IDs from the playlist and then analyze each ID to get the data from the videos, but the script is too slow, although it should be stressed that it works well, is there any way to optimize it?...
function youtube_automusic($listas, $api_key, $resultados){
$nresultados = $resultados;
$lista_reproduccion_random = $listas;
$lista_reproduccion = $lista_reproduccion_random[array_rand($lista_reproduccion_random)];
$url_playlist = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&fields=items(snippet(resourceId(videoId)))&type=video&videoCategoryId=10&maxResults=".$nresultados."&playlistId=".$lista_reproduccion."&key=".$api_key;
$data = dlPage($url_playlist);
$data_decode = json_decode($data, true);
$number_song = 1;
$respuesta = array();
foreach ($data_decode as $items){
foreach ($items as $item){
$lista_ids =$item['snippet']['resourceId']['videoId'];
$url_video = "https://www.googleapis.com/youtube/v3/videos?id=".$lista_ids."&part=snippet,contentDetails&fields=items(etag,id,snippet(publishedAt,title,thumbnails(default(url)),tags),contentDetails(duration))&key=".$api_key;
$data_video = dlPage($url_video);
$data_video_decode = json_decode($data_video, true);
foreach ($data_video_decode as $items_videos){
foreach ($items_videos as $item_video){
$data_final = array(
'etag' => $item_video['etag'],
'idvideo' => $item_video['id'],
'titulovideo' => $item_video['snippet']['title'],
'thumbnail' => $item_video['snippet']['thumbnails']['default']['url'],
'duracion' => $item_video['contentDetails']['duration'],
'videoplay' => $number_song++
);
array_push($respuesta, $data_final);
}
}
}
}
return json_encode($respuesta);
}
With your code on a 50 item playlist it would take 51 API calls.
Instead of doing a single videos request for each video in the playlist, get all the video IDs in the playlist first and then make videos requests for up to 50 at a time (the ID parameter takes a comma-separated list of up to 50 items).
Then a 50 item playlist would only take 2 API calls.
Should be much faster.
I just ran a test here
Request:
GET https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails&id=Ks-_Mh1QhMc&fields=items(etag%2Cid%2Csnippet(publishedAt%2Ctitle%2Cthumbnails(default(url))%2Ctags)%2CcontentDetails(duration))&key={YOUR_API_KEY}
Results:
{
"items": [
{
"etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/aCBUdsaX0W34z3It8a8FCh5uteo\"",
"id": "Ks-_Mh1QhMc",
"snippet": {
"publishedAt": "2012-10-01T15:27:35.000Z",
"title": "Your body language may shape who you are | Amy Cuddy",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/default.jpg"
}
},
"tags": [
"Amy Cuddy",
"TED",
"TEDTalk",
"TEDTalks",
"TED Talk",
"TED Talks",
"TEDGlobal",
"brain",
"business",
"psychology",
"self",
"success"
]
},
"contentDetails": {
"duration": "PT21M3S"
}
}
]
}
I suggest that you run the same request using the Google APIs Explorer using the video id that you are having an issue with to verify that its not an issue with the API not returning your duration.

Facebook API get post details from feed [duplicate]

This question already has answers here:
Facebook JS SDK's FB.api('/me') method doesn't return the fields I expect in Graph API v2.4+
(4 answers)
Closed 7 years ago.
I'm using the PHP Facebook API (together with laravel)
I can manage to get the feed from a page, with all it's post using
$request = Facebook::get('/COMPANYPAGE?fields=feed.limit(25)');
$response = $request->getGraphPage()->getField('feed');
This returns the following objects
But I can't seem to get the specific information for that post! Like
the images included.. Is there another call I need to perform?
I tried the following but it's giving me back the same results
$request = Facebook::get('/elbeko?fields=feed.limit(25)');
$response = $request->getGraphPage()->getField('feed');
foreach($response as $item) {
$post = Facebook::get($item['id'])->getGraphObject();
}
From v2.4 on, you have to specify each field you want to have returned from the Grpah API. You should be able to use
/elbeko/feed?fields=id,message,link,attachments{media}&limit=25
which returns something like
{
"data": [
{
"id": "1472127519670095_1645415342341311",
"message": "Benieuwd naar ons nieuw project in de regio Gent? Binnenkort meer info via www.elbeko.be!",
"link": "https://www.facebook.com/elbeko/photos/a.1589552831260896.1073741835.1472127519670095/1645415342341311/?type=3",
"attachments": {
"data": [
{
"media": {
"image": {
"height": 405,
"src": "https://scontent.xx.fbcdn.net/hphotos-xpl1/v/t1.0-9/s720x720/11954813_1645415342341311_5204470874884096944_n.jpg?oh=0a7e10b12d3feb90b2de79fa60a7f8f8&oe=56C30337",
"width": 720
}
}
}
]
}
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.5/1472127519670095/feed?fields=id,message,link,attachments%7Bmedia%7D&limit=2&format=json&since=1441790055&access_token=&__paging_token=&__previous=1",
"next": "https://graph.facebook.com/v2.5/1472127519670095/feed?fields=id,message,link,attachments%7Bmedia%7D&limit=2&format=json&access_token=&until=1441124382&__paging_token="
},
}
See
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.5#fields
https://developers.facebook.com/docs/apps/upgrading#v23tov24
https://developers.facebook.com/docs/graph-api/reference/v2.5/post
In the past, responses from Graph API calls returned a set of default fields. In order to reduce payload size and improve latency on mobile networks we have reduced the number of default fields returned for most Graph API calls. In v2.4 you will need to declaratively list the response fields for your calls.

YouTube API v3 get latest video uploads for a username with PHP

I am trying to get a list of a user's latest videos/uploads. I am trying to get my head around this new v3 API, but I cannot find any properly working PHP code examples, not even on the dedicated YouTube API website.
I have a list of YouTube usernames, and I just want to simply get a list of their latest videos with video ID, title, thumbnail URL, etc. Basically in a foreach loop.
Any advice?
I have the following code, I need to make it work by the actual YouTube usernames.
$url = 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=ferrariworld&key=ZZZZZZZZ';
$json = json_decode(file_get_contents($url), true);
foreach ($json as $item){
echo $item[0]['id'];
echo $item[0]['title'];
}
Use the channels endpoint with a forUsername attribute (see the documentation for the endpoint).
GET https://www.googleapis.com/youtube/v3/channels?part=id&forUsername={USERNAME}&key={YOUR_API_KEY}
It will give you this kind of response:
{
"kind": "youtube#channelListResponse",
"etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/7Q8DJLb6b2hwYAXUQLI3ftt3R8U\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/pDjr9xPn51KtRM3gbMOq2aHBIbY\"",
"id": "UCr3LuetcEeidWiuhxaw4B2g"
}
]
}
The channel ID of that user can be found at items[0]['id'] if you convert the JSON to array.
As for your edit, you’re accessing the JSON object incorrectly. You need to use something like this.
if (array_key_exists('items', $json) && count($json['items']) === 1) {
$item = $json['items'][0];
$channelId = $item['id']; // The users channel ID.
}

Looking for effiicient way to pull data from facebook graph api

I've been recently working with facebook graph api , when I'm pulling user's recents status messages using https://graph.facebook.com/me/statuses?access_token=... all I get is a long list which contains details about the status content, and I want to pull the names of people who liked the status.
The current solution I've been thinking about is using preg match,
I'd like to know if you guys have any other suggestions,
Thanks in advance
I'm not sure what path you're using, but you can fetch the list of users who like a particular status update by requesting the likes connection on an update.
For example, requesting https://graph.facebook.com/10150710880081168/likes yields something like the following for me:
{
"data": [
{
"id": "276700623",
"name": "Vikki Carter"
},
{
"id": "1514365200",
"name": "Darren Bean"
},
{
"id": "539760281",
"name": "Ian Sidaway"
}
],
"paging": {
"next": "https://graph.facebook.com/10150710880081168/likes?format=json&limit=25&offset=25&__after_id=539760281"
}
}
You'll need the ID of the status update, but also the user_status permission from the logged-in user.
EDIT: Iterating over the returned data and assigned users into an array:
<?php
$result = $facebook->api('[status_id]/likes');
$names = array();
foreach ($result['data'] as $user) {
$names[] = $user['name'];
}
You should now have an array of names of users who liked the status in question.

Categories