How to Make a Responsive YouTube Video in WordPress Without Plugins
The article appeared for two reasons., I did not find good plugins for implementing adaptive videos from YouTube, and also since it worked for me i decided to share this experience with you.
In fact, developing another website for a client, he decided to insert a YouTube video into the article. Plugin previously used, was removed for unknown reasons from the repository and I started looking for solutions and thinking, how to solve this issue.
In order for a video to become responsive, there are a lot of examples on the Internet when it is wrapped in a separate DIV tag and styles are added to it., WordPress doesn't have this tag by default., therefore, the first thing to do is to add a hook that will work with the content part and wrap, for example, a frame in the desired tag.
YouTube Responsive Video Hook Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php add_filter('the_content', function($content) { return str_replace(array("<iframe", "</iframe>"), array('<div class="iframe-container"><iframe', "</iframe></div>"), $content); }); add_filter('embed_oembed_html', function ($html, $url, $attr, $post_id) { if(strpos($html, 'youtube.com') !== false || strpos($html, 'youtu.be') !== false){ return '<div class="embed-responsive embed-responsive-16by9">' . $html . '</div>'; } else { return $html; } }, 10, 4); add_filter('embed_oembed_html', function($code) { return str_replace('<iframe', '<iframe class="embed-responsive-item" ', $code); }); |
YouTube Responsive Output Styles Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
.embed-responsive { position: relative; display: block; height: 0; padding: 0; overflow: hidden; } .embed-responsive .embed-responsive-item, .embed-responsive iframe { position: absolute; top: 0; bottom: 0; left: 0; width: 100%; height: 100%; border: 0; } .embed-responsive-16by9 { padding-bottom: 56.25%; } |
/*
- Basic web design course;
- Site layout;
- General course on CMS WordPress and continuation of the course on template development;
- Website development in PHP.