The purpose
Here are two ways to embed a YouTube video in a webpage.
How to specify a video in an iframe using the src attribute
The first method is to specify the video using the src
attribute in an iframe.
This is typically how YouTube videos are embedded.
How to embed
Obtained code from a video
Obtain the HTML code by right-clicking a YouTube video and selecting “Copy embed code” from the menu that appears.

The following code is obtained.
<iframe width="1033" height="581" src="https://www.youtube.com/embed/XXXXXXX" title="Video title" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
You can also change the video being played by manually changing the ID part (“XXXXXXX” in the example above) and the Title part (“Video title” in the example above) in the src
attribute.
Embedding in WordPress
In WordPress, you can embed a YouTube video by simply pasting its URL (e.g., https://www.youtube.com/watch?v=XXXXXXXXXX&t=4s) at the beginning of a paragraph.
Of course, you can also embed it using the YouTube block.
Embedding with the YouTube Player API
The second method is embedding using the YouTube Player API.

As explained on the page above, the examples provided are somewhat difficult to use (the very first one is unusable as is), so this page introduce some revised, more user-friendly versions.
Implementation
The code is as follows.
html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>動画埋め込み</title>
</head>
<body>
<div id="player"></div>
<script src="youtube.js"></script>
</body>
</html>
youtube.js
let tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
let player_element = document.getElementById('player')
player_element.parentNode.insertBefore(tag, player_element);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'XXXXXXXXXX',
});
}
By modifying the videoId
(XXXXXXXXXX above) in JavaScript, you can change the video that is played.
Benefit
While it might seem like embedding a YouTube video using the YouTube Player API is more trouble than it’s worth based on what we’ve seen so far, there are significant advantages.
The key benefit is the ability to manipulate the video player from JavaScript. For example, you can create a custom control panel for the embedded video using JavaScript.
(I haven’t tried it, but it might be possible to manipulate a video by specifying its source (src) in an iframe and then accessing the video tag from within the iframe. However, this won’t work locally due to browser security policies. The only significant advantage of this method is the ability to test it locally.)
comment