WordPressに埋め込むyoutubeを自動レスポンシブ化

Filed under: functions.php,wordpress — kdcs @ 18年3月30日 金曜日

WordPressの記事にyotubeを埋め込む場合、埋め込みタグをそのまま貼り付けると決まった固定サイズになる

これをレスポンシブに対応させるためにはyoutubeコードのiframeをdivで囲う必要があるのでfunction.phpに以下の記述を行う。

function iframe_in_div($the_content) {
if ( is_singular() ) {
$the_content = preg_replace('/<iframe/i', '<div class="youtube"><iframe', $the_content);
$the_content = preg_replace('/<\/iframe>/i', '</iframe></div>', $the_content);
}
return $the_content;
}
add_filter('the_content','iframe_in_div');

これで「youtube」というクラスが付いたdivタグがiframeに付加される

あとはyoutubeというクラスにcssを記述する

.youtube {
position: relative;
width: 100%;
padding-top: 56.25%;
}
.youtube iframe{
position: absolute;
top: 0;
right: 0;
width: 100% !important;
height: 100% !important;
}

横幅90%で中央配置にする場合

.youtube {
position: relative;
width: 90%;
margin: 0 auto;
padding-top: 56.25%;
}
.youtube iframe{
position: absolute;
top: 0;
right: 0;
width: 100% !important;
height: 100% !important;
}

サイト内検索

カテゴリー

最近の投稿

« |WordPressに埋め込むyoutubeを自動レスポンシブ化| »
↑上に戻る