How To Automatically Embed The Latest Video From A YouTube Channel?

Embed the latest or second latest video from any youtube channel using javascript method or iframe method.
automatically embed latest video from youtube channel

If you happen to own both a blog and a youtube channel, then you might have a “My Youtube Channel” widget on your site to display your latest videos. But updating this widget every time you upload a video can be a hefty and monotonous work. Not anymore! Now you can automatically embed the latest video from a youtube channel with a single line of code.

Auto Embed Latest Video from a Youtube Channel

<iframe width="600" height="340" src="https://www.youtube.com/embed?max-results=1&controls=0&showinfo=0&rel=0&listType=user_uploads&list=YOUR_CHANNEL_NAME_HERE" frameborder="0" allowfullscreen></iframe>

In the above code snippet, replace the channel name placeholder with your channel name. The snippet won’t work with channel IDs so make sure to add the correct channel name itself.

Copy-paste the code into an online HTML code editor to see its working.

Auto Embed Latest/Second Latest Video from Youtube Channel

With this method, you can embed the latest, second latest or third latest video from any youtube channel by knowing it’s channel ID. The channel ID should be replaced in the cid parameter of the iframe. To load the latest video use the parameter vnum='0' and for second latest use vnum='1' and so on.

<iframe class="latestVideoEmbed" vnum='0' cid="UCBJycsmduvYEL83R_U4JriQ" width="600" height="340" frameborder="0" allowfullscreen></iframe>
<iframe class="latestVideoEmbed" vnum='1' cid="UC0xXUfNSFQN3qOmf_G_nT5w" width="600" height="340" frameborder="0" allowfullscreen></iframe>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var reqURL = "https://api.rss2json.com/v1/api.json?rss_url=" + encodeURIComponent("https://www.youtube.com/feeds/videos.xml?channel_id=");
function loadVideo(iframe) {
  $.getJSON(reqURL + iframe.getAttribute('cid'),
    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=0&autoplay=1");
    }
  );
}
var iframes = document.getElementsByClassName('latestVideoEmbed');
for (var i = 0, len = iframes.length; i < len; i++) {
  loadVideo(iframes[i]);
}
</script>

See the code in action in the here.

If this worked for you, please leave an upvote to my answer at StackOverflow.

Total
75
Shares
6 comments
  1. Thank you so much! It worked the first time I tried. I don’t have a channel name yet, so this was my first foray into embedding JavaScript and Ajax into a WordPress page. Very happy.

Leave a Reply
Related Posts
Total
73
Share