Trong bài này chúng ta sẽ làm cho iframe video của youtube full-width và responsive. Qua bài Cách lấy Youtube video ID từ URL, Get ID, times length and thumbnail image youtube video by URL và Chèn video youtube vào wordpress bằng shortcode chúng ta cũng hiểu rõ hơn về các lấy ID và chèn video vào bài viết.
Thêm 1 DIV bao khoanh iFrame trong bài viết
Đoạn code này sẽ giúp chúng ta thêm 1 DIV bao quanh iframe của video youtube. Thêm vào file functions.php
<?php /* * Add to functions.php * Add div.videoWrapper to iframe */ function div_wrapper($content) { // match any iframes /*$pattern = '~<iframe.*</iframe>|<embed.*</embed>~'; // Add it if all iframe*/ $pattern = '~<iframe.*src=".*(youtube.com|youtu.be).*</iframe>|<embed.*</embed>~'; //only iframe youtube preg_match_all($pattern, $content, $matches); foreach ($matches[0] as $match) { // wrap matched iframe with div $wrappedframe = '<div class="videoWrapper">' . $match . '</div>'; //replace original iframe with new in content $content = str_replace($match, $wrappedframe, $content); } return $content; } add_filter('the_content', 'div_wrapper'); ?>
Css để respon
Thêm đoạn code css này vào file style.css của theme
.videoWrapper { position: relative; padding-bottom: 56.25%; /* 16:9 */ padding-top: 25px; height: 0; } .videoWrapper iframe, .videoWrapper object, .videoWrapper embed{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
Chúc các bạn thành công!
Từ khóa: youtube responsive
- Bình luận