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.
const requestOptions = {
method: 'GET',
redirect: 'follow'
};
const loadVideo = (iframe) => {
const cid = iframe.getAttribute('cid');
const channelURL = encodeURIComponent(`https://www.youtube.com/feeds/videos.xml?channel_id=${cid}`)
const reqURL = `https://api.rss2json.com/v1/api.json?rss_url=${channelURL}`;
fetch(reqURL, requestOptions)
.then(response => response.json())
.then(result => {
const videoNumber = (iframe.getAttribute('vnum') ? Number(iframe.getAttribute('vnum')) : 0);
const link = result.items[videoNumber].link;
const id = link.substr(link.indexOf("=") + 1);
iframe.setAttribute("src", `https://youtube.com/embed/${id}?controls=0&autoplay=1`);
})
.catch(error => console.log('error', error));
}
var iframes = document.getElementsByClassName('latestVideoEmbed');
for (var i = 0, len = iframes.length; i < len; i++) {
loadVideo(iframes[i]);
}
See the code in action in the here.
If this worked for you, please leave an upvote to my answer at StackOverflow.
how do i add auto play option, its only playing when clicked the play button
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.
How add more than 1 channel with ID?
Hi! I’m trying to adapt it to the labnol embedding way, that is lighter than embed an iframe.
https://www.labnol.org/internet/light-youtube-embeds/27941/
Do you know how do adapt that?
Thanks!
Hello dear ! I was trying to find that everywhere but without any luck ! Could you share also a code for the latest 1 or 2 videos from a playlist ?
Hello, can I load more than 10 videos with this script? How?
Thanks