0

I want to get 4 videos retrieved randomly from a channel id with YouTube API V3. So I want that when I refresh the page the videos retrieved change. The script I'm creating is in PHP language, a custom plugin inside a Wordpress site.

Now I use this api call, but this retrieve always same videos:

$api_call = "https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=".$channelId."&maxResults=4&key=".$YouTube_API_key."";

There is a way to get videos randomly by YouTube API?

If someone think I have to rand myself with php functions like rand, but I have to get all videos, so if I have 200 videos and maxResults can only be max 50 value, i can't do it by that way.

steplab
  • 11
  • 6
  • Possible duplicate of [How do I get a random YouTube video with the YouTube API?](https://stackoverflow.com/questions/11315416/how-do-i-get-a-random-youtube-video-with-the-youtube-api) – Raymond Nijland Jun 19 '17 at 15:22
  • If it's not your channel (where you means the OAuth autorized user) then it's not possible to get more than 50 videos. You can change the order parameter but still some videos will never come up. I think this is intentional. – apokryfos Jun 19 '17 at 16:14
  • @apokryfos no, is owned channel, so you tell me I can retrieve more than 50 videos? How to do that? – steplab Jun 20 '17 at 07:20

2 Answers2

0

I'd recommend a three-pronged approach:

  • Build a database to store links to each of your videos.
  • Run a nightly cron job to keep the database up to date with new uploads.
  • When you need a random video, select the videos from your database and pick a random row.
Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83
0

Each result you get should have a nextPageToken in it if there's a next page of data available. For example:

{
"kind": "youtube#searchListResponse",
 "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/3McBp6TfA-1T7NXO6x9Lr5WXpKI\"",
 "nextPageToken": "CBkQAA",
 "regionCode": "GB",
     "pageInfo": {
     "totalResults": 1000000,
  "resultsPerPage": 25
}

You can construct an additional request using that as a pageToken and that will get you the next page of results if there's more than 1 page. e.g.

 $nextApiCall = "https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=<>&pageToken=CBkQAA";

You can keep making API calls until you've reached the "totalResults" number (or there's no more next page tokens).

After you've gotten all results you can just do array_rand to get a random index from the array.

apokryfos
  • 38,771
  • 9
  • 70
  • 114