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

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.

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.

Exit mobile version