How to Embed Multiple YouTube Videos on Your Website

Boost your YouTube growth through your website

How to Embed Multiple YouTube Videos on Your Website

Photo by Rachit Tank on Unsplash

While working on my Django-made website, I realized that it would make a lot of sense to pair it with my YouTube channel so as to grow the two platforms simultaneously. This process was quite a learning experience for me so I thought I’d write an article to help share what I’ve learnt along the way.

One of the main reasons for joining both my website and YouTube account was that this offered the potential for me to increase the size of my audience (when you add YouTube videos to a website there is a high chance that you will be able to reach a wider audience using your website). Another upshot of doing this is that having a personal website increases your credibility so it is one of the best ways to grow on the YouTube platform. It seemed like a perfect marriage to me: YouTube could bring new visitors to my website, and my website would direct some visitors to my YouTube channel.

This article will also guide you through arranging YouTube videos into a Grid view (thanks to materializecss). An added bonus here is that this program will update and organize the videos automatically on your website whenever you post a new one, meaning that you won’t have to look back at the code again.

How to Add YouTube Videos to your Website

First, let’s have a look at how to add a specific video.

Specific videos

Screenshot from my upcoming websiteScreenshot from my upcoming website

For specific videos, you just need the YouTube video ID, which you can get from the URL and paste it in the code below. For example- [https://youtu.be/xQsTLQevgdI](youtu.be/xQsTLQevgdI) for this URL video ID is xQsTLQevgdI.

<iframe width="420" height="315"
src="https://www.youtube.com/embed/LN54KeRkvPo"> <!-- put your video ID after embed/ -->
</iframe>

The above code will display your YouTube video wherever you want it to appear on the site. You can experiment with CSS to display it according to your website design. I recommend using materializecss because it makes the job much easier.

Videos in Grid format

Screenshot of grid view from my upcoming websiteScreenshot of grid view from my upcoming website

If you want all of your videos, or a certain number of videos, to be displayed on your website then you can use a grid view. I have implemented this on my Django website, but the same code can be modified to work with any other framework. To implement this correctly, you need to retrieve the JSON data for your YouTube videos, to do this you can use an API called rss2json. Just open the website, paste your YouTube channel URL in the field, press ‘convert to JSON’ button, and you will find an API call like this one:

**API call: [https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3DUCDXQNb3linY9EksWAvJhPyQ](https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3DUCDXQNb3linY9EksWAvJhPyQ)**

This will allow us to get all of the data that we need to upload the video and get info about the video such as title, release date, URL, etc.

Please note: You only need to carry out the following step if you’re using Django, otherwise you can skip this step.

import urllib.request as urllib2
import json

def videos(request):
  reqURL =  " https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3DUCDXQNb3linY9EksWAvJhPyQ&api_key=mll6zmdtx5s3w48ti7g1hdbrpjgzssl23q36c8ml&count=1000"
  response = urllib2.urlopen(reqURL)
  data = json.loads(response.read())
  value = len(data['items'])
  print(value)
  if value % 2 == 0:
    #total = [i for i in range(value)]
    i = [i for i in range(0,value,2)]
    j = [j for j in range(1,value,2)]
  else:
    #total = [i for i in range(value+1)]  
    i = [i for i in range(0,value+1,2)]
    j = [j for j in range(1,value+1,2)]

  print(i,j)
  return render(request = request,
                template_name = 'main/videos.html',
                context = {'list':zip(i,j)})

Paste the API call URL in the place of existing reqURL (this will allow us to get the JSON data for the YouTube channel). The above code is only required if you are working with Django. This is because Django has a model-view-controller architecture and you can send data from the Python code to an HTML template. The above function gets the total number of videos on our YouTube channel and creates two lists, i and j. if you have 10 videos in your channel, the list will look something like this:

i = [0,2,4,6,8]

j = [1,3,5,7,9]

We then pass this data to our HTML file in the following format:

[0,1

2,3

4,5
... and so on]

If you want to know more about Django, here is an excellent post by Kristian Roopnarine How to create a web app with Django. A three part Django series. In this part we install Django, start the development server and load our first template.medium.com

This concludes the Django section. The following code will make it clear why we need this:

{% extends "main/footer.html" %}
<html>

<head>

  {% load static %}
  <link rel="stylesheet" type="text/css" href="{% static 'main/css/obj_detection.css'%}">
  <link rel="stylesheet" type="text/css" href="{% static 'main/css/home.css'%}">

  <style type="text/css">
    /* unvisited link */
  </style>
</head>


{% block content %}

<body style="background-color: #696969;"></body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container" style="padding-top: 50px;">

  {% for i,j in list %}

  <div class="row">
    <div class="col s6 m6">
      <div data-aos="fade-right" data-aos-duration="2000" data-aos-once="false" class=" video-container"
        style="padding-top: 7%;">
        <iframe class="latestVideoEmbed" vnum='{{i}}' cid="UCDXQNb3linY9EksWAvJhPyQ" frameborder="0" allowfullscreen
          style="border: 5px solid #ffffff; padding: 5px;"></iframe>
      </div>
    </div>

    <div class="col s6 m6">
      <div data-aos="fade-left" data-aos-duration="2000" data-aos-once="false" class=" video-container"
        style="padding-top: 7%;">
        <iframe class="latestVideoEmbed" vnum='{{j}}' cid="UCDXQNb3linY9EksWAvJhPyQ" frameborder="0" allowfullscreen
          style="border: 5px solid #ffffff; padding: 5px;"></iframe>
      </div>
    </div>

  </div>
  {% endfor %}

</div>

<script>

  var reqURL = "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3DUCDXQNb3linY9EksWAvJhPyQ&api_key=mll6zmdtx5s3w48ti7g1hdbrpjgzssl23q36c8ml&count=1000";
  function loadVideo(iframe) {
    $.getJSON(reqURL,
      function (data) {
        var videoNumber = (iframe.getAttribute('vnum') ? Number(iframe.getAttribute('vnum')) : 0);
        console.log(videoNumber);

        var link = data.items[videoNumber].link;
        id = link.substr(link.indexOf("=") + 1);
        iframe.setAttribute("src", "https://youtube.com/embed/" + id + "?controls=1&autoplay=0"); //change controls to 0 if you don't want controls to be displayed, and set autoplay to 1 if you want it to play automatically

      }
    );
  }

  var iframes = document.getElementsByClassName('latestVideoEmbed');
  var span = document.getElementsByClassName('card-title'); // use to get the title of the video
  for (var i = 0, len = iframes.length; i < len; i++) {
    loadVideo(iframes[i]);
  }

</script>
</body>
{% endblock %}

</html>

This is the HTML file; the frontend of our website. The portion after{% for i,j in list %} is the main part. This loop takes our zip object from videos()function and uses the i and j values to create the required grid. &lt;div class=”row”&gt; this tag creates a row with two columns for two videos and the loop creates more of these types of rows, creating a grid. Between the &lt;div&gt; tags, we have &lt;iframe&gt; tag to display the YouTube video. It requires few arguments such as cid (channel id) and vnum (i,j, i.e the number of the video that needs to be displayed) The &lt;script&gt; tag has the code to get the URL of each video and send it to &lt;iframe&gt; tag to display it.

Conclusion

That’s it, now you can house your YouTube videos on your website as you see fit! Your website is now more dynamic (as you have another media type on your page through the inclusion of videos), gives the viewer a better feel for who you are and where your interests lie, and helps you grow your online presence. If you have any doubts or know a better way of enacting what I laid out in this article, please let me know in the responses.

Did you find this article valuable?

Support Shubh Patni by becoming a sponsor. Any amount is appreciated!