WEB系キャンパス

WorPressでYoutubeの埋め込みのレスポンシブ対応する2つの方法

今までYoutubeといえば、iframeが一般的だったけど、
WordPressのoEmbedっていう機能で、自動的にアイフレームに切り替えてくれるみたい。

↓記事内にURLをいれると…

※共通リンクでも、ツールバーに表示されてるURLでもどっちでもOK

↓こうなる

1<p><iframe width="560" height="315" src="https://www.youtube.com/embed/OmsAkXakEuA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></p>

【1】JetPackが入ってる場合はCSSを追加するのみ

JetPackが入っている場合は、YoutubeのURLをいれるだけで、自動的にiframeの前後にclassが追加される

↓こんな感じ

1<p><span class='embed-youtube' style='text-align:center; display: block;'><iframe width="560" height="315" src="https://www.youtube.com/embed/OmsAkXakEuA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></span></p>

あとはCSSを追加するだけ

1.embed-youtube {
2    position: relative;
3    display: block;
4    width: 100%;
5    height: 0;
6    padding-bottom: 56.25%;
7    overflow: hidden;
8    margin-bottom: 25px;
9}
10.embed-youtube iframe {
11    width: 100%;
12    height: 100%;
13    position: absolute;
14    top: 0;
15    left: 0;
16}

【2】JetPackが入っていない場合はfunctions.phpをちょっといじる

functions.phpに下記のコードを追加

1//YouTubeのURLにclassを付与
2function custom_youtube_oembed($code){
3  if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){
4    $html = preg_replace("@src=(['\"])?([^'\">\s]*)@", "src=$1$2&showinfo=0&rel=0", $code);
5    $html = preg_replace('/ width="\d+"/', '', $html);
6    $html = preg_replace('/ height="\d+"/', '', $html);
7    $html = '<div class="youtube">' . $html . '</div>';
8 
9    return $html;
10  }
11  return $code;
12}
13 
14add_filter('embed_handler_html', 'custom_youtube_oembed');
15add_filter('embed_oembed_html', 'custom_youtube_oembed');

これで、抽出されるHTMLをはこうなる

1<div class="youtube">
2 <iframe src="https://www.youtube.com/embed/OmsAkXakEuA?feature=oembed&#038;showinfo=0&#038;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
3</div>

あとは、CSSを追記(class名以外さっきと同じ)

1.youtube {
2    position: relative;
3    display: block;
4    width: 100%;
5    height: 0;
6    padding-bottom: 56.25%;
7    overflow: hidden;
8    margin-bottom: 25px;
9}
10.youtube iframe {
11    width: 100%;
12    height: 100%;
13    position: absolute;
14    top: 0;
15    left: 0;
16}

参考サイト

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です