WordPress embed ショートコードで埋め込んだ YouTube 動画のレスポンシブ対応
やりたいこと
- iframeタグの前後に任意のdivを挿入し、CSSでレスポンシブ対応させる
- アスペクト比は16:9のみ対応とする
- 動画の埋め込みには embed ショートコードを使用する
- post_contentにあたる部分を置換するのではなく、embed機能のなにがしかにフックして書き換たい
- 個別投稿かつYouTube動画の埋め込みにだけ効かせる
使用例
投稿本文での書き方
[embed]https://www.youtube.com/watch?v=wgp4pGbl_wU[/embed]
または
[embed]https://youtu.be/wgp4pGbl_wU[/embed]
※ショートコード変換走らないように大括弧を全角にしてます。
ソース
functions.php
参考:embed_oembed_html | Hook | WordPress Developer Resources
User Contributed Notes に寄せられていたソースを改変(そのままだと動作しなかったため)。
function wrap_oembed_html( $cached_html, $url, $attr, $post_id ) { if( strpos($cached_html,'youtube') !== false || strpos($cached_html,'youtu.be') !== false ){ $cached_html = '<div class="embed-responsive">'.$cached_html.'</div>'; } return $cached_html; } add_filter( 'embed_oembed_html', 'wrap_oembed_html', 99, 4 );
展開されるHTML
<div class="embed-responsive"><iframe title="ニガミ17才 MV「こいつらあいてる」(Nigami 17th birthday!! "koitsura_ aiteru)" src="https://www.youtube.com/embed/wgp4pGbl_wU?feature=oembed" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="500" height="281" frameborder="0"></iframe></div>
CSS
Bootstrap 3 にある Responsive embed のソースを抜き出した。
.embed-responsive{ position: relative; display: block; width: 100%; padding: 0; overflow: hidden; padding-top: 56%; } .embed-responsive iframe{ position: absolute; top: 0; bottom: 0; left: 0; width: 100%; height: 100%; border: 0; z-index: 0; }