先日アップした方法では、WordPressで使用した場合、どうもjQueryのバージョンによってはうまく動作しない事があった。
なので今回は、jQueryは使わず、PHPを用いた方法を解説♪
WordPressでもうまくいくし、PHPが使える環境だったらこっちの方がいいかもね☆
PHPとCSSでYouTube動画をレスポンシブ対応させる方法
まずは以下コードをstyle.css等のメインCSSファイルに書き込む。
.video{
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
}
.video iframe{
position: absolute;
top: 0;
left: 0;
width: 100%!important;
height: 100%!important;
}
次にfunction.phpに以下のPHPコードを追加して、YouTubeが貼られたページが読み込まれた際に、YouTubeタグを<div class="video"></div>で囲って上記CSSが適用される処理をする。
これは、以下2つの方法から目的に合った方を使えば良いと思われ。
①サイト内のiframeすべてに適用
サイト内のiframeすべてに適用させるので、YouTube以外でiframeを使う箇所がある場合は誤動作を起こす可能性がある。
<?php
function div_sounyuu($the_content) {
if (is_singular()){
$the_content = preg_replace('/<iframe/i', '<div class="video"><iframe', $the_content);
$the_content = preg_replace('/<\/iframe>/i', '</iframe></div>', $the_content);
}
return $the_content;
}
add_filter('the_content','div_sounyuu');
?>
②youtubeのみに適用
YouTube関連のiframeにのみ適用させる。
ただし、正規表現を用いるので、①の方法より理論上処理速度は劣る。
まあ体感はできないだろうけど。
function div_sounyuu($the_content){
preg_match_all('/<iframe.*youtube.com*.\/iframe>/i', $the_content, $matches);
foreach ($matches as $match){
foreach ($match as $m){
$the_content= str_replace($m, '<div id="video">'.$m.'</div>', $the_content);
}
}
return $the_content;
}
add_filter('the_content','div_sounyuu');
?>
以上。
コメント