Developers

Custom YouTube Hashtag and Channel Playlists

Custom YouTube Hashtag and Channel Playlists

Design your own video strategy with custom playlists

At RebelMouse, we have the ability to implement almost any idea thanks to the power of our Layout & Design Tool. One use case is the ability to easily create custom YouTube playlists based on hashtags.

For example, if your company uses the #OurCompany hashtag, you could create a custom YouTube playlist on your website that pulls in content from that stream. You can also customize the playlist so that it only pulls in videos from a certain YouTube channel, or from a single channel without a hashtag:


The key to creating a custom playlist is to use YouTube's API to pull content. Let's explore how to pull content based on a hashtag, regardless of the channel.

Query for a Playlist Based on a Hashtag

The first step is to create a JavaScript variable for the query that will pull from the YouTube API. For example:

var queryStr = 'https://www.googleapis.com/youtube/v3/search?part=snippet&q=' + queryHash + '&type=video&videoCaption=any&videoDefinition=any&videoDimension=any&videoDuration=any&videoEmbeddable=any&videoLicense=any&videoSyndicated=any&videoType=any&key=' + key + '&maxResults='+maxResults;

For playlists based just on hashtags, there are three required parameters:

  • QueryHash: Your custom hashtag.
  • MaxResults: Fetch x videos, where x equals the maximum number of videos you want to pull. It can be any positive integer value.
  • Key: The API key. (This will be shared by the owner of the YouTube channel. See this guide that describes how to get an API key.)
  • ChannelId: This is an optional parameter. If it's provided in your query, it will only fetch videos from the channel ID you designate, otherwise it will fetch videos from any channel. Click here to learn how to locate a channel's ID.

Query for Playlists Based on Hashtags From a Single Channel

Here is the API query using the ChannelId parameter:

https://www.googleapis.com/youtube/v3/search?part=snippet&q=' + queryHash + '&type=video&videoCaption=any&videoDefinition=any&videoDimension=any&videoDuration=any&videoEmbeddable=any&videoLicense=any&videoSyndicated=any&videoType=any&key=' + key + '&maxResults=' + maxResults + '&channelId='+ channelId;

Understanding the JavaScript Logic

Now that we have an understanding of which query strings to use when making requests to the YouTube API, let's dive into how the JavaScript logic works

The basic idea is that we use the fetch API built into modern browsers to make Ajax requests to the YouTube API. Next, it fetches a response in JSON, and then we parse it and display the response in a video format using iframes.

Here is an example of a JSON response from the YouTube API:

{
 "kind": "youtube#searchListResponse",
 "etag": "\"Fznwjl6JEQdo1MGvHOGaz_YanRU/zdxYH_AS29xYgdx2YxQYxPeLj-I\"",
 "nextPageToken": "CAEQAA",
 "regionCode": "IN",
 "pageInfo": {
  "totalResults": 12,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"Fznwjl6JEQdo1MGvHOGaz_YanRU/77ZWdQpKmM3r0vin9RorTTevnQc\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "iv0N7i2virY"
   },
   "snippet": {
    "publishedAt": "2019-07-04T08:40:09.000Z",
    "channelId": "UCJv753whZjpW22UfmaJbx4Q",
    "title": "From Kurils with Love: The Expedition Trailer",
    "description": "On Monday, the 8th July, an unusual expedition is setting sails in the town of Petropavlovsk in Kamchatka. A group of filmmakers, adventurers, climbers, ...",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/iv0N7i2virY/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/iv0N7i2virY/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/iv0N7i2virY/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "Tomorrow Unlocked",
    "liveBroadcastContent": "none"
   }
  }
 ]
}

Sample Code

Below are some sample codes for using JavaScript to fetch a response for videos based on a hashtag and then render them as an iframe video player:

<div class="hash-videos"></div><button id="load-more-videos" class="load-more" onclick="LoadMore()">Load More</button><style>
.hash-videos {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 100%;
}
.yt-iframe {
margin: 0px 10px 0px 0px;
width: 340px;
padding: 5px;
}
/* tablets */
@media screen and (min-width: 768px) and (max-width: 1023px) {
 .yt-iframe {
  margin: 0 auto;
  width: 50%;
  box-sizing: border-box;
  }
}
  /* small devices */
@media screen and (max-width:767px) {
  .yt-iframe {
  margin: 0;
  width: 100%;
  padding: 0 0 15px 0;
  }
}
.load-more {
background: black;
border: 1px solid;
padding: 10px 20px;
width: 200px;
margin: 40px auto 50px;
display: block;
font-size: 15px;
}
</style><script>
  var queryHash = ""; //"fromkurilswithlove";
  var maxResults = 6;
  var key = "AIzaSyC5PqJgz18fIBjd9Yq3eA6cmL3EfmrbL1w";
  var pageToken = "";  // Pagination Logic.
  var channelId = "UCJv753whZjpW22UfmaJbx4Q"; // TomorrowUnlocked
  function LoadMore() {
 fetch('https://www.googleapis.com/youtube/v3/search?part=snippet&q=' + queryHash + '&type=video&videoCaption=any&videoDefinition=any&videoDimension=any&videoDuration=any&videoEmbeddable=any&videoLicense=any&videoSyndicated=any&videoType=any&channelId='+ channelId +'&key=' + key + '&maxResults='+maxResults+'&pageToken='+pageToken)
    .then(
      function(response) {
        if (response.status !== 200) {
          console.log('Looks like there was a problem. Status Code: ' +
            response.status);
          return;
        }
        // Examine the text in the response
        response.json().then(function(data) {
          renderVideos(data);
          console.log(data);
        });
      }
    )
    .catch(function(err) {
      console.log('Fetch Error :-S', err);
    });
  }
  function renderVideos(data) {
    console.log(data.items.length);
    var videosData = data.items;
    var playerFrame = document.getElementsByClassName("hash-videos")[0];
    console.log(playerFrame);    
    for(var i = 0; i < videosData.length; i++) {
        /*<div class='yt-iframe'><iframe title='' type='text/html' src='http://www.youtube.com/embed/id frameborder='0' allowFullScreen></iframe><div>*/
        var ytdiv = document.createElement("div");
        ytdiv.setAttribute("class","yt-iframe");
          var ytIframe = document.createElement("iframe");
          ytIframe.setAttribute("src", "https://www.youtube.com/embed/" + videosData[i].id.videoId);
        ytIframe.setAttribute("title", videosData[i].snippet.title);
        ytIframe.setAttribute("allowFullScreen", "true")
        ytIframe.setAttribute("frameborder", 0);
        ytIframe.setAttribute("width","340px");
        ytdiv.appendChild(ytIframe);
        playerFrame.appendChild(ytdiv);
    }
    //check if we have more videos else hide load more button
    if(data.nextPageToken) {
      pageToken = data.nextPageToken; //YT response gives a token for next page fetch.
    } else {
      pageToken = "";
      var x = document.getElementById("load-more-videos");
      x.style.display = "none";
    }
  }
  LoadMore();
</script>

If you have any questions or need help implementing this or any other feature — depending on the nature of the request, it may require services hours from us to complete the work — please email support@rebelmouse.com or talk to your account manager today.

What Is RebelMouse?
Request a Proposal

Where 
Websites Are Built

The Fastest Sites in the World Run on RebelMouse

Let’s Chat

new!

RebelMouse Performance Monitoring

Real-Time Core Web Vitals

Get Started
DISCOVER MORE

Our Core Features

Our platform is a complete digital publishing toolbox that's built for modern-day content creators, and includes game-changing features such as our:

animate
Layout and Design toolLayout and Design tool on mobile
animate

Why RebelMouse?

Unprecedented Scale

RebelMouse sites reach more than 120M people a month, with an always-modern solution that combines cutting-edge technology with decades of media savvy. And due to our massive scale, 1 in 3 Americans have visited a website powered by RebelMouse.

120M+ Users
550M+ Pageviews
17+ Avg. Minutes per User
6+ Avg. Pages per User

Today's Top Websites Use RebelMouse

Thanks to the tremendous scale of our network, we are able to analyze a wealth of traffic data that informs our strategies and allows us to be a true strategic partner instead of just a vendor.

upworthyindy100Vault12No Film SchoolRawStoryResponsible StatecraftPrideRolling Stone QuebecPremierGuitarPenskeINN Educate Brand ConnectThe FulcrumGZEROOkayafricaBrit+CoPaper MagazinePowerToFlyNarcityCommonDreamsAllBusiness

What Clients Say

We’re here to help you weigh and understand every tech and strategic decision that affects your digital presence. Spend less time managing everything yourself, and more time focused on creating the quality content your users deserve.

Case Studies

A Team (and an Agency) Built Like No Other

RebelMouse employs a unique, diverse, and decentralized team that consists of 70+ digital traffic experts across more than 25 different countries. We have no central office, and we cover every time zone to ensure that we’re able to deliver amazing results and enterprise-grade support around the clock.

Our team is well-versed in all things product, content, traffic, and revenue, and we strategically deploy ourselves to help with each element across all of our clients. We thrive on solving the complex.

Let's Chat